验证XML节点,而不是整个文档 [英] Validating xml nodes, not the entire document

查看:119
本文介绍了验证XML节点,而不是整个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与形成向下的XML元素某些XML片段工作。我有模式,而是因为他们是不完整的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?

我工作在C#.NET与2.0框架。

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节点,而不是整个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆