2010-08-05 2 views
2

Я не знаю достаточно о пространстве имен XML, чтобы увидеть мою ошибку. Вы?Как проверить XML против схемы (XSD)? Что-то не так

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> 

Этот метод должен возвращать ложь, но она возвращает истину.

Честно говоря, я не уверен, с чего начать отлаживать это. : S

Заранее благодарю за ваше время и ответ.

+1

Вместо того, чтобы ловить исключение и возвращать 'false', вы можете позволить ему взорвать и вырезать-n-paste исключение, которое вы получаете? – sarnold

ответ

Смежные вопросы