代碼示例本來很好,可以確定你在做什麼,但是我可以做出一些假設,因爲我在同一個地方。我遇到了Using XSDs with includes,並調整了我接受的答案。
問題是,XmlReader
似乎不知道包含的模式的基本路徑是什麼,如果您沒有指定它,而Create()
的XmlReader
。假設您有一個到您的XML文件的文件路徑,請使用XmlReader.Create(Stream input, XmlReaderSettings settings, String baseUri)
並將XML文件的路徑作爲baseUri
。
例子:
using System.IO;
using System.Xml;
using System.Xml.Schema;
public void LoadXml(string path) {
XmlDocument doc = new XmlDocument();
XmlReader docReader;
XmlReaderSettings rdrOpts = new XmlReaderSettings();
rdrOpts.ValidationType = ValidationType.Schema;
rdrOpts.ValidationFlags = XmlSchemaValidationFlags.ProcessSchemaLocation;
try {
// This line is what you're looking for:
docReader = XmlReader.Create(new FileStream(path, FileMode.Open, FileAccess.Read), rdrOpts, Path.GetDirectoryName(path));
doc.Load(docReader);
} catch (System.Xml.Schema.XmlSchemaValidationException ex) {
//...
} //and catch any other relevant exceptions here, like System.IO.FileNotFoundException
}
什麼是整個例外(`ex.ToString()`)?它可能會告訴你行號和位置,甚至可能是文件名。 – 2011-01-21 23:31:28