【问题标题】:XML validation by XSD: Could not find schema information for the elementXSD 的 XML 验证:找不到元素的架构信息
【发布时间】:2013-11-20 08:38:19
【问题描述】:

有一个XML:

<?xml version="1.0" encoding="utf-8" ?>
 <FirstSection FirstSectionAttr="5" >
   <SecondSection Value="0x15"/>
   <SecondSection Value="10"/>
 </FirstSection>

有一个 XSD(由 VS 创建):

<?xml version="1.0" encoding="utf-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:element name="FirstSection">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="unbounded" name="SecondSection">
          <xs:complexType>
            <xs:attribute name="Value" type="xs:string" use="required" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
      <xs:attribute name="FirstSectionAttr" type="xs:unsignedByte" use="required" />
    </xs:complexType>
  </xs:element>
</xs:schema>

有一个验证码:

    static void Validate(string xsdPath, string fullFileName)
    {
        try
        {
            var settings = new XmlReaderSettings();
            settings.Schemas.Add("http://www.w3.org/2001/XMLSchema", xsdPath);
            settings.ValidationType = ValidationType.Schema;
            settings.ValidationEventHandler += OnXmlValidationEventError;
            settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings;

            using (var reader = XmlReader.Create(fullFileName, settings))
            {
                while (reader.Read())
                {

                }
            }
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
        }

    }

    private static void OnXmlValidationEventError(object sender, ValidationEventArgs e)
    {
        try
        {
            Console.WriteLine("Problem: " + e.Message);
        }
        catch (Exception exception)
        {
            Console.WriteLine(exception);
        }
    }

代码返回:

问题:找不到元素“FirstSection”的架构信息。

问题:找不到属性“FirstSectionAttr”的架构信息。

问题:找不到元素“SecondSection”的架构信息。

问题:找不到属性“值”的架构信息。

问题:找不到元素“SecondSection”的架构信息。

问题:找不到属性“值”的架构信息。

如何正确验证?

【问题讨论】:

    标签: .net xml validation xsd


    【解决方案1】:

    为您的文档添加默认命名空间

    <FirstSection FirstSectionAttr="5" xmlns="http://www.w3.org/2001/XMLSchema">
    

    或者在没有命名空间的情况下注册您的架构

    settings.Schemas.Add(null, xsdPath);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-22
      相关资源
      最近更新 更多