.NET 中的 XML 验证和命名空间 [英] XML validation and namespaces in .NET

查看:16
本文介绍了.NET 中的 XML 验证和命名空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做的是根据 XSD 验证 XML.这一切都非常简单,但是我在使用没有命名空间的 XML 时遇到了问题.如果命名空间与 XSD 的目标命名空间匹配,C# 仅验证 xml.这似乎是正确的,但是没有命名空间或与 SchemaSet 不同的 XML 应该给出一个例外.是否有属性或设置来实现这一目标?还是必须通过读取 xml 的 xmlns 属性手动获取命名空间?

What I'm trying to do is to validate XML against an XSD. This is all pretty straightforward, but I'm having a problem with XML's without a namespace. C# only validates the xml if the namespace matches the targetnamespace of the XSD. This seems right, but an XML with no namespace or a different one then the SchemaSet should give an exception. Is there a property or a setting to achieve this? Or do I have to get the namespace manually by reading the xmlns attribute of the xml?

澄清示例:

代码:

XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add("http://example.com", @"test.xsd");
settings.Schemas.Add("http://example.com/v2", @"test2.xsd");
settings.ValidationType = ValidationType.Schema;

XmlReader r = XmlReader.Create(@"test.xml", settings);

XmlReader r = XmlReader.Create(new StringReader(xml), settings);
XmlDocument doc = new XmlDocument();
try
{
    doc.Load(r);
}
catch (XmlSchemaValidationException ex)
{

    Console.WriteLine(ex.Message);
}

XSD:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com" targetNamespace="http://example.com" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:element name="test">
        <xs:annotation>
            <xs:documentation>Comment describing your root element</xs:documentation>
        </xs:annotation>
        <xs:simpleType>
            <xs:restriction base="xs:string">
                <xs:pattern value="[0-9]+\.+[0-9]+" />
            </xs:restriction>
        </xs:simpleType>
    </xs:element>
</xs:schema>

有效的 XML:

<test xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</test>

无效的 XML,这不会验证:

Invalid XML, this will not validate:

<hello xmlns="http://example.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>

错误:未声明http://example.com:hello"元素.

无效的 XML,但会验证,因为命名空间不存在:

Invalid XML, but will validate, because namespace is not present:

<hello xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">112.1</hello>

我该如何解决这个问题?

How can I fix this?

非常感谢任何帮助.

推荐答案

xml 中无效的命名空间没有触发 XmlSchemaValidationException 的原因是,因为它只是一个警告.

The reason why invalid namespaces in the xml aren't triggering the XmlSchemaValidationException , is, because it is just a warning.

因此,我们必须更改代码,以便同时报告警告.

So, we have to change the code so warnings are also reported.

First:在 XmlReaderSettings

XmlReaderSettings settings = new XmlReaderSettings();
settings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints | XmlSchemaValidationFlags.ReportValidationWarnings;

PS:通过设置验证标志,确保您设置了所有需要的标志,否则一些验证检查将被跳过.我正在使用 ProcessIdentityConstraints,所以我的身份约束(xs:key, xs:keyref,...) 也被验证.更多信息请访问 http://msdn.microsoft.com/en-us/library/system.xml.schema.xmlschemavalidationflags.aspx.

PS:By setting validation flags, make sure you set all the flags needed, otherwise some validationchecks will be skipped. I'm using ProcessIdentityConstraints, so my identity-constraints(xs:key, xs:keyref,...) are also validated. More info at http://msdn.microsoft.com/en-us/library/system.xml.schema.xmlschemavalidationflags.aspx.

Next:告诉验证器在报告警告时要做什么.创建一个 Validator 事件,当发生警告或错误时会触发该事件

Next: tell the validator what to do when a warning is reported. Create a Validator event, that will be triggered when a warning or error occurs

private static void SchemaValidatorHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Warning || e.Severity == XmlSeverityType.Error)
        {
            //Handle your exception
        }



    }

最后:设置要用于验证的验证器事件处理程序

Last: Set the validator event handler you want to use for your validation

settings.ValidationEventHandler += new ValidationEventHandler(SchemaValidatorHandler);

就这样

这篇关于.NET 中的 XML 验证和命名空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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