问题描述
我正在使用一些在 xml 中形成元素的 xml 'snippets'.我有架构,但我无法验证这些文件,因为它们不是完整的 xml 文档.这些片段包含必要的父元素以在其他工具中使用它们时形成有效的 xml,因此我没有太多选择将它们变成有效的 xml 或更改架构.
I'm working with some xml 'snippets' that form elements down the xml. I have the schema but I cannot validate these files because they are not complete xml documents. These snippets are wrapped with the necessary parent elements to form valid xml when they are used in other tools so I don't have much option in making them into valid xml or in changing the schema.
是否可以验证一个元素,而不是整个文档?如果没有,可以建议哪些解决方法?
Is it possible to validate an element, rather than the whole document? If not, what workarounds could be suggested?
我正在使用带有 .NET 2.0 框架的 C#.
I'm working in C# with .NET 2.0 framework.
推荐答案
我遇到了类似的问题,我只能验证部分 XML 文档.我在这里想出了这个方法:
I had a similar problem where I could only validate parts of my XML document. I came up with this method here:
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);
using (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);
}
基本上,我将一个 XmlNode(我通过 .SelectSingleNode 从整个 XmlDocument 中选择)和一个 XML 模式传递给它,我从我的应用程序内的嵌入式资源 XSD 加载它.任何可能发生的验证错误都被填充到错误"字符串构建器中,然后我在最后读出它,看看是否记录了任何错误.
Basically, I pass it an XmlNode (which I select from the entire XmlDocument by means of .SelectSingleNode), and an XML schema which I load from an embedded resource XSD inside my app. Any validation errors that might occur are being stuffed into a "errors" string builder, which I then read out at the end, to see if there were any errors recorded, or not.
为我工作 - 你的里程可能会有所不同:-)
Works for me - your mileage may vary :-)
这篇关于验证 xml 节点,而不是整个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!