XML通过XSD验证:找不到元素的模式信息

5

这里有一个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”的模式信息。
问题:无法找到属性“Value”的模式信息。
问题:无法找到元素“SecondSection”的模式信息。
问题:无法找到属性“Value”的模式信息。
如何正确验证?
1个回答

10

要么在您的文档中添加一个默认命名空间

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

或者在不使用命名空间的情况下注册您的模式

settings.Schemas.Add(null, xsdPath);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接