我正在尝试在保存之前验证我在代码中创建的 XML 文档。但是,即使我故意输入不正确的值,我的代码也总是毫无问题地通过验证。代码有什么问题?
private XmlDocument xmlDocChanges = new XmlDocument();
public void Validate()
{
xmlDocChanges.Schemas.Add("http://www.w3.org/2001/XMLSchema", "xsd/Customization.xsd");
ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationCallBack);
xmlDocChanges.Validate(eventHandler);
}
public void ValidationCallBack (object sender, ValidationEventArgs args)
{
if(args.Severity == XmlSeverityType.Error || args.Severity == XmlSeverityType.Warning)
{
throw new Exception(args.Exception.Message);
}
}
编辑示例 XSD。
<?xml version="1.0" encoding="utf-8"?>
<xs:schema
attributeFormDefault="unqualified"
elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:complexType name="FirstNode">
<xs:annotation>
<xs:documentation>First node</xs:documentation>
</xs:annotation>
<xs:attribute name="Identifier" type="xs:string" use="required" />
<xs:attribute name="Bool" type="xs:boolean" use="optional" />
</xs:complexType>
</xs:schema>
XML
<Customizations FormatVersion="1" xsi:noNamespaceSchemaLocation="Customization.xsd">
<Customization>
<Application name="App">
<FirstNode Identifier="one" Bool="NoValue"></FirstNode>
</Application>
</Customization>
</Customizations>