通过 XSD 文件验证 XML 节点 [英] validating XML node over a XSD file
问题描述
我正在尝试根据 XML 架构验证 XML 节点或片段.我已经阅读了这篇文章:
I'm trying to validate XML nodes or fragments against an XML schema. I have read this article:
但所选择的解决方案似乎不适合我.
but the chosen solution doesn't look like to work for me.
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"
wich is, as far as I can see, the code for validate a full document, but with "ConformanceLevel.Fragment"
例如,有一个像这样简单的模式:
Thus, for example, having a schema as simple as this:
<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>
但任何内部节点都不会验证
But any inner node doesn't validate
<Address>
<Line1>Foo</Line1>
<Line2>Foo2</Line2>
</Address>
我收到错误消息:'Address' 元素未声明"
I receive the error: "'Address' element is not declared"
有什么我遗漏的吗?
推荐答案
在 MiMo 的推荐下,为了解决这个问题我在 RUNTIME 修改了 schema.我将其加载到内存中并在那里进行更改.我在这里发布了我的解决方案:
Following the recomendation of MiMo, to solve the problem I modify IN RUNTIME the schema. I load it in memory and change it there. I posted my solution here:
这篇关于通过 XSD 文件验证 XML 节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!