我有这个XML文件
<bookstore>
<test>
<test2/>
</test>
</bookstore>
和这个XSD架构
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="test" type="xsd:anyType" />
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
我打算从 C# 代码验证 xml 文件。有一种验证 XML 文件的方法:
// validate xml
private void ValidateXml()
{
_isValid = true;
// Get namespace from xml file
var defaultNamespace = XDocument.Load(XmlFileName).Root.GetDefaultNamespace().NamespaceName;
// Set the validation settings.
XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationType = ValidationType.Schema;
settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
settings.Schemas.Add(defaultNamespace, XsdFileName);
settings.ValidationEventHandler += OnValidationEventHandler;
// Create the XmlReader object.
using(XmlReader reader = XmlReader.Create(XmlFileName, settings))
{
// Parse the file.
while (reader.Read()) ;
}
}
private void OnValidationEventHandler(object s, ValidationEventArgs e)
{
if (_isValid) _isValid = false;
if (e.Severity == XmlSeverityType.Warning)
MessageBox.Show("Warning: " + e.Message);
else
MessageBox.Show("Validation Error: " + e.Message);
}
我知道,这个 XML 文件是有效的。但是我的代码重新出现了这个错误:
Validation Error: Could not find schema information for the element 'test2'
我的错误在哪里?
谢谢!!!