使用 XSD 架构的 Xml 验证 [英] Xml validation using XSD schema
问题描述
以下代码帮助我验证具有 XSD 架构的 XML 文件.
The following code helps me validate an XML file with an XSD schema.
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(null, xsdFilePath);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(settings_ValidationEventHandler);
XmlDocument document = new XmlDocument();
document.Load(xmlFilePath);
XmlReader rdr = XmlReader.Create(new StringReader(document.InnerXml), settings);
while (rdr.Read())
{
}
isValid = true;
ValidationEventHandler 还告诉我错误是什么,但没有告诉我它们位于哪里"或在哪一行".有没有什么办法可以得到XML验证失败的行号?
The ValidationEventHandler also tells me what the errors are, but doesn't tell me on 'where' or 'on which line' they are located. Is there any way to get the line number where the XML fails to be validated?
推荐答案
这不是你想要的吗?
创建一个 XmlReaderSettings
对象并通过该对象启用警告.
Create an
XmlReaderSettings
object and enable warnings through that object.
不幸的是,似乎无法将您自己的 XmlReaderSettings
对象传递给 XmlDocument.Validate()
.
相反,您可以使用验证 XmlReader
和 XmlNodeReader
来验证现有的 XmlDocument
(使用带有 XmlNodeReader
的 XmlNodeReader
code>StringReader 而不是 XmlDocument
)
Unfortunately, there seems to be no way to pass your own XmlReaderSettings
object to XmlDocument.Validate()
.
Instead, you can use a validating XmlReader
and an XmlNodeReader
to validate an existing XmlDocument
(using a XmlNodeReader
with StringReader
rather than an XmlDocument
)
XmlDocument x = new XmlDocument();
x.LoadXml(XmlSource);
XmlReaderSettings settings = new XmlReaderSettings();
settings.CloseInput = true;
settings.ValidationEventHandler += Handler;
settings.ValidationType = ValidationType.Schema;
settings.Schemas.Add(null, ExtendedTreeViewSchema);
settings.ValidationFlags =
XmlSchemaValidationFlags.ReportValidationWarnings |
XmlSchemaValidationFlags.ProcessIdentityConstraints |
XmlSchemaValidationFlags.ProcessInlineSchema |
XmlSchemaValidationFlags.ProcessSchemaLocation ;
StringReader r = new StringReader(XmlSource);
using (XmlReader validatingReader = XmlReader.Create(r, settings)) {
while (validatingReader.Read()) { /* just loop through document */ }
}
和处理程序:
private static void Handler(object sender, ValidationEventArgs e)
{
if (e.Severity == XmlSeverityType.Error || e.Severity == XmlSeverityType.Warning)
System.Diagnostics.Trace.WriteLine(
String.Format("Line: {0}, Position: {1} "{2}"",
e.Exception.LineNumber, e.Exception.LinePosition, e.Exception.Message));
}
这篇关于使用 XSD 架构的 Xml 验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!