2012-05-14 158 views
2

我有這個XML文件的Xml XSD驗證失敗(XS:anyType的)

<bookstore> 
    <test> 
    <test2/> 
    </test> 
</bookstore> 

XSD架構

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element name="bookstore" type="bookstoreType"/>  
    <xsd:complexType name="bookstoreType"> 
    <xsd:sequence maxOccurs="unbounded"> 
     <xsd:element name="test" type="xsd:anyType" /> 
    </xsd:sequence>          
    </xsd:complexType> 
</xsd:schema> 

我打算驗證從C#代碼的XML文件。 有是驗證XML文件的方法:

// validate xml 
    private void ValidateXml() 
    { 
     _isValid = true; 

     // Get namespace from xml file 
     var defaultNamespace = XDocument.Load(XmlFileName).Root.GetDefaultNamespace().NamespaceName; 

     // Set the validation settings. 
     XmlReaderSettings settings = new XmlReaderSettings(); 
     settings.ValidationType = ValidationType.Schema; 
     settings.ValidationFlags |= XmlSchemaValidationFlags.ReportValidationWarnings; 
     settings.Schemas.Add(defaultNamespace, XsdFileName); 
     settings.ValidationEventHandler += OnValidationEventHandler; 

     // Create the XmlReader object. 
     using(XmlReader reader = XmlReader.Create(XmlFileName, settings)) 
     { 
      // Parse the file. 
      while (reader.Read()) ;  
     } 
    } 

    private void OnValidationEventHandler(object s, ValidationEventArgs e) 
    { 
     if (_isValid) _isValid = false; 

     if (e.Severity == XmlSeverityType.Warning) 
      MessageBox.Show("Warning: " + e.Message); 
     else 
      MessageBox.Show("Validation Error: " + e.Message); 
    } 

我知道,這個XML文件是有效的。但我的代碼reterns this錯誤:

Validation Error: Could not find schema information for the element 'test2' 

我的錯誤在哪裏?

謝謝!

+0

看看這個問題http://stackoverflow.com/questions/5389076/difference-similarities-between-xsdany-and-xsdanytype – Jodrell

回答

1

更新:我假設您的代碼與您列出的錯誤相匹配(我在.NET 3.5SP1上嘗試過您的代碼,但無法重現您的行爲)。下面的解決方法應該可以正常工作(您得到的錯誤與流程內容子句strict相反,而不是lax)。

一個複雜的內容,允許XSD更換<xsd:element name="test" type="xsd:anyType" />:有,像這樣:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <xsd:element name="bookstore" type="bookstoreType"/> 
    <xsd:complexType name="bookstoreType"> 
     <xsd:sequence maxOccurs="unbounded"> 
      <xsd:element name="test"> 
       <xsd:complexType> 
        <xsd:sequence> 
         <xsd:any minOccurs="0" maxOccurs="unbounded" processContents="lax"/> 
        </xsd:sequence> 
       </xsd:complexType> 
      </xsd:element> 
     </xsd:sequence> 
    </xsd:complexType> 
</xsd:schema> 

有「寬鬆」仍然將產生一個消息;如果你想消息消失,你可以使用「跳過」。無論如何,skiplax在一個xsd:任何給你你所需要的。

+1

我有點驚訝,你接受了這個答案。這可能是一個解決方法,但它不能解釋爲什麼原件失敗。因此我是低調的。正如你正確地指出的那樣,你的XML實例對你的XSD模式是有效的,而我爲人不明白爲什麼它會失敗。 –

+1

@MichaelKay,我同意答案沒有明確說明一件事情:我已經提供了一種可能是錯誤或編碼錯誤的解決方法。 –