XmlDocument.验证不支持的属性或元素

本文关键字:元素 属性 验证 不支持 XmlDocument | 更新日期: 2023-09-27 18:27:31

如果 xml 中的属性或元素未在 xsd 中定义,我如何获取验证事件。

xsd:

    <?xml version="1.0" encoding="utf-8"?>
    <xsd:schema id="VoiceXmlTSPro"
                targetNamespace="http://tempuri.org/VoiceXmlTSPro.xsd"
                elementFormDefault="qualified"
                xmlns="http://tempuri.org/VoiceXmlTSPro.xsd"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!-- Elements-->
    <xsd:element name="vxml">
     <xsd:complexType>
      <xsd:attribute ref="base"/>
      <xsd:attribute ref="lang"/>
      </xsd:complexType>
     </xsd:element> 
       <!-- End Elements-->
       <!-- Attributes-->
       <xsd:attribute name="base" type="xsd:anyURI">
     </xsd:attribute>
     <xsd:attribute name="lang" type="xsd:string"> 
     </xsd:attribute>
    <!-- End Attributes-->
  </xsd:schema>

.xml:

    <?xml version="1.0" encoding="utf-8" ?>
     <vxml application="notsupported" lang="en-US"     base="http://www.zebra.com">
       <unknow></unknow>
      </vxml>

我想要一个关于应用程序属性和未知的警告。但是这段代码不会引发任何事件。

    public override void Validate(string source)
    {
        ValidationResults.Clear();
        XmlSchemaFactory xmlSchemaFactory = new XmlSchemaFactory();
        XmlReaderSettings vxmlTestSettings = new XmlReaderSettings();
        vxmlTestSettings.ValidationType = ValidationType.Schema;
        vxmlTestSettings.ValidationFlags = XmlSchemaValidationFlags.ProcessIdentityConstraints| XmlSchemaValidationFlags.ReportValidationWarnings ;
        try
        {
            XmlSchema xsdSchema = xmlSchemaFactory.Create(Resource.VoiceXmlTSPro);
            if (xmlSchemaFactory.HasErrors())
            {
                // if the schema is invalid the read wil not read
                return;
            }
            vxmlTestSettings.Schemas.Add(xsdSchema);
            ValidationEventHandler eventHandler = new ValidationEventHandler(ValidationHandler);
            using (MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(source)))
            using (XmlReader xmlReader = XmlReader.Create(stream, vxmlTestSettings))
            {
                XmlDocument document = new XmlDocument();
                document.Load(xmlReader);
                document.Validate(eventHandler);
            }
        }
        catch (Exception ex)
        {
            ...
        }
    }

XmlDocument.验证不支持的属性或元素

如果您需要做的就是根据架构验证 XML 标记的字符串,然后使用具有适当XmlReaderSettingsStringReaderXmlReader解析字符串,则无需使用 XmlDocument 及其Validate方法。

下面是一个示例,对于

第一个示例,它仅输出警告,因为输入文档没有命名空间声明,对于第二个文档,存在有关未声明元素和属性的错误:

    static void Main(string[] args)
    {
        string[] xmls = { @"<vxml application=""notsupported"" lang=""en-US""     base=""http://www.zebra.com"">
   <unknow></unknow>
  </vxml>",
        @"<vxml application=""notsupported"" lang=""en-US""     base=""http://www.zebra.com"" xmlns=""http://example.com/ns1"">
   <unknow></unknow>
  </vxml>"
                        };
        foreach (string xml in xmls)
        {
            Console.WriteLine("Validating");
            Validate(xml, "../../schema1.xml");
            Console.WriteLine();
        }
    }
    static void Validate(string xmlMarkup, string schemaUri)
    {
        XmlReaderSettings xrs = new XmlReaderSettings();
        xrs.Schemas.Add(null, schemaUri);
        xrs.ValidationType = ValidationType.Schema;
        xrs.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;
        xrs.ValidationEventHandler += (obj, valArgs) =>
        {
            Console.WriteLine("{0}: {1}", valArgs.Severity, valArgs.Message);
        };
        using (StringReader sr = new StringReader(xmlMarkup))
        {
            using (XmlReader xr = XmlReader.Create(sr, xrs))
            {
                while (xr.Read()) { }
            }
        }
    }

架构为

<?xml version="1.0" encoding="utf-8" ?> 
<xsd:schema id="VoiceXmlTSPro"
                targetNamespace="http://example.com/ns1"
                elementFormDefault="qualified"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <!-- Elements-->
    <xsd:element name="vxml">
     <xsd:complexType>
      <xsd:attribute name="base" type="xsd:anyURI"/>
      <xsd:attribute name="lang" type="xsd:string"/>
      </xsd:complexType>
     </xsd:element> 
       <!-- End Elements-->
  </xsd:schema>

输出为

Validating
Warning: Could not find schema information for the element 'vxml'.
Warning: Could not find schema information for the attribute 'application'.
Warning: Could not find schema information for the attribute 'lang'.
Warning: Could not find schema information for the attribute 'base'.
Warning: Could not find schema information for the element 'unknow'.
Validating
Error: The 'application' attribute is not declared.
Error: The element cannot contain white space. Content model is empty.
Error: The element 'http://example.com/ns1:vxml' cannot contain child element 'http://example.com/ns1:unknow' because the parent element's content model is empty.