如何验证XML对架构(XSD)?出了点问题

时间:2010-08-05 08:52:22

标签: c# xml xsd schema validation

我不太了解XML命名空间以查看我的错误。你呢?

    public static bool ValidateXml(string xml, string xsd)
    {
        try
        {
            // build XSD schema

            StringReader _XsdStream;
            _XsdStream = new StringReader(xsd);

            XmlSchema _XmlSchema;
            _XmlSchema = XmlSchema.Read(_XsdStream, null);

            // build settings (this replaces XmlValidatingReader)

            XmlReaderSettings _XmlReaderSettings;
            _XmlReaderSettings = new XmlReaderSettings()
            {
                ValidationType = ValidationType.Schema
            };
            _XmlReaderSettings.Schemas.Add(_XmlSchema);

            // build XML reader

            StringReader _XmlStream;
            _XmlStream = new StringReader(xml);

            XmlReader _XmlReader;
            _XmlReader = XmlReader.Create(_XmlStream, _XmlReaderSettings);

            // validate

            using (_XmlReader)
            {
                while (_XmlReader.Read())
                    ;
            }

            // validation succeeded

            return true;
        }
        catch
        {
            // validation failed

            return false;
        }
    }

这是XSD

<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://server.com/www/content" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="ads">
  <xs:complexType>
    <xs:sequence>
      <xs:element maxOccurs="unbounded" name="ad">
        <xs:complexType>
          <xs:attribute name="id" type="xs:string" use="required" />
          <xs:attribute name="date" type="xs:string" use="required" />
          <xs:attribute name="checksum" type="xs:string" use="required" />
          <xs:attribute name="size" type="xs:string" use="required" />
          <xs:attribute name="expanded-size" type="xs:string" use="required" />
        </xs:complexType>
      </xs:element>
    </xs:sequence>
    <xs:attribute name="last-modified" type="xs:string" use="required" />
  </xs:complexType>
</xs:element>
</xs:schema>

这是XML

<?xml version="1.0" encoding="UTF-8" ?>
<ads xmlns="http://server.com/www/content" last-modified="">
    <ad id="ad1" date="" checksum="" size="" expanded-size=""/>
    <ad id="ad2" date="" checksum="" size="" expanded-size=""/>
    <ad id="ad3" date="" checksum="" size="" expanded-size=""/>
</ads>

该方法应该返回false,但它返回true。

老实说,我不知道从哪里开始调试这个。 :S

提前感谢您的时间和答案。

1 个答案:

答案 0 :(得分:0)

用XmlValidatingReader替换XMLReader以进行验证。请参阅:http://msdn.microsoft.com/en-us/library/system.xml.xmlvalidatingreader_members%28v=VS.71%29.aspx