为什么 XmlDocument.validate 会错误地验证具有空命名空间的无效 xml 文档? [英] Why does XmlDocument.validate incorrectly validate an invalid xml document with empty namespaces?

查看:17
本文介绍了为什么 XmlDocument.validate 会错误地验证具有空命名空间的无效 xml 文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证我在代码中创建的 XML 文档,然后再保存它.但是,即使我故意输入不正确的值,我的代码也始终可以毫无问题地通过验证.代码有什么问题?

I'm trying to validate a XML document I'm creating in the code before i save it. However my code always pass through the validation with no problem even when i input incorrect value on purpose. What is the problem with the code?

private XmlDocument xmlDocChanges = new XmlDocument();
   public void Validate()
   {
        xmlDocChanges.Schemas.Add("http://www.w3.org/2001/XMLSchema", "xsd/Customization.xsd");
        ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationCallBack);
        xmlDocChanges.Validate(eventHandler);
   }
   public void ValidationCallBack (object sender, ValidationEventArgs args)
   {
       if(args.Severity == XmlSeverityType.Error || args.Severity == XmlSeverityType.Warning)
       {
           throw new Exception(args.Exception.Message);
       }
   } 

编辑示例 XSD.

    <?xml version="1.0" encoding="utf-8"?>
<xs:schema
    attributeFormDefault="unqualified"
    elementFormDefault="qualified"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:complexType name="FirstNode">
    <xs:annotation>
      <xs:documentation>First node</xs:documentation>
    </xs:annotation>
    <xs:attribute name="Identifier" type="xs:string" use="required" />
    <xs:attribute name="Bool" type="xs:boolean" use="optional" />
  </xs:complexType>
</xs:schema>

XML

<Customizations FormatVersion="1" xsi:noNamespaceSchemaLocation="Customization.xsd">
  <Customization>
    <Application name="App">
      <FirstNode Identifier="one" Bool="NoValue"></FirstNode>
    </Application>
  </Customization>
</Customizations>

推荐答案

我找到了解决方案.我不得不在 add 方法中发送一个空的命名空间参数.

I found a solution. I had to send a empty namespace parameter in the add method.

    public void Validate()
    {
        xmlDocChanges.Schemas.Add("", "xsd/Customization.xsd");
        ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationCallBack);
        xmlDocChanges.Validate(eventHandler);
    }
    public void ValidationCallBack (object sender, ValidationEventArgs args)
    {
        if(args.Severity == XmlSeverityType.Error || args.Severity == XmlSeverityType.Warning)
        {
            throw new Exception(args.Message);
        }
    }

这篇关于为什么 XmlDocument.validate 会错误地验证具有空命名空间的无效 xml 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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