代码之家  ›  专栏  ›  技术社区  ›  Jerry Nixon

如何根据模式(XSD)验证XML?出了点问题

  •  2
  • Jerry Nixon  · 技术社区  · 16 年前

    我对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 回复  |  直到 14 年前
        1
  •  0
  •   Kangkan    16 年前