如果 xml 文档没有对 XML Schema 的引用,一切正常
<Application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.companyname.com/blabla"
xmlns="http://www.companyname.com/blabla">
但是,如果 xml 引用了本地机器上的模式,如下所示:
<Application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.companyname.com/blabla
Schemas\myschema.xsd"
xmlns="http://www.companyname.com/blabla">
这会导致错误“已声明全局元素‘TopElementName’。
XmlReaderSettings xrs = new XmlReaderSettings();
xrs.ValidationType = ValidationType.Schema;
xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessInlineSchema;
xrs.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
//xsd is located (intalled) in this same location where myapp.exe is.
string startLoc = System.Reflection.Assembly.GetExecutingAssembly().Location;
string xsd = Path.Combine(Path.GetDirectoryName(startLoc), "myschema.xsd");
using (Stream schemaStr = new FileStream(xsd, FileMode.Open))
{
XmlSchema s = XmlSchema.Read(schemaStr, null);
xrs.Schemas.Add(s);
}
xrs.Schemas.Compile();
using (XmlReader r = XmlReader.Create(xmlPath, xrs))
{
while (r.Read()){}
r.Close();
}
如何避免这个错误?