我正在尝试针对 XML 模式验证 XML 节点或片段。我读过这篇文章:
但选择的解决方案看起来不适合我。
private void ValidateSubnode(XmlNode node, XmlSchema schema)
{
XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null);
XmlReaderSettings settings = new XmlReaderSettings();
settings.ConformanceLevel = ConformanceLevel.Fragment;
settings.Schemas.Add(schema);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new ValidationEventHandler(XSDValidationEventHandler);
XmlReader validationReader = XmlReader.Create(reader, settings);
while (validationReader.Read())
{
}
}
private void XSDValidationEventHandler(object sender, ValidationEventArgs args)
{
errors.AppendFormat("XSD - Severity {0} - {1}",
args.Severity.ToString(), args.Message);
}
据我所知,这是验证完整文档的代码,但带有“ConformanceLevel.Fragment”
因此,例如,有一个像这样简单的模式:
<xsd:schema xmlns:xsd='http://www.w3.org/2001/XMLSchema'>
<xsd:element name="Customer">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Address">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Line1" type="xsd:string" />
<xsd:element name="Line2" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>
“根”节点验证 OK
<Customer>
<Address>
<Line1>Foo</Line1>
<Line2>Foo2</Line2>
</Address>
</Customer>
但是任何内部节点都不会验证
<Address>
<Line1>Foo</Line1>
<Line2>Foo2</Line2>
</Address>
我收到错误:“'地址'元素未声明”
有什么我想念的吗?