2010-08-05 72 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> 

的方法應該返回假,但它返回true。

老實說,我不知道從哪裏開始調試。 :S

預先感謝您的時間和答覆。

+1

而不是捕獲異常並返回'false',您能讓它炸燬並剪切n粘貼您收到的異常嗎? – sarnold 2010-08-05 08:57:45

回答