2012-07-01 162 views
5

鑑於架構(匿名,感興趣的關鍵點被重命名,其餘略):爲什麼此XDocument驗證失敗?

Dim xDocument = 
<x:inspec xmlns:x='the_right_namespace'> 
<a_collection_property/> 
<another_collection_property/> 
</x:inspec> 

驗證失敗的:

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema id="inspec" 
    targetNamespace="the_right_namespace" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
> 
    <xs:element name="inspec"> 
    <xs:complexType> 
     <xs:all> 
     <xs:element name="a_scalar_property" type="xs:int"/> 
     <xs:element name="a_collection_property"> 
      <xs:complexType> 
      <snip> 
      </xs:complexType> 
     </xs:element> 
     <xs:element name="another_collection_property"> 
      <xs:complexType>     
      <snip> 
      </xs:complexType> 
     </xs:element>      
     </xs:all> 
    </xs:complexType> 
    </xs:element> 
</xs:schema> 

和實例(使用VB XML文本聲明)消息The element 'inspec' in namespace 'the_right_namespace' has incomplete content. List of possible elements expected: 'a_scalar_property'.

爲什麼?根據W3Schools的all元素:

「all元素指定子元素可以以任何順序出現,並且每個子元素可以出現零次或一次。」

省略a_scalar_property與將其包括零次相同。爲什麼這個文件無法驗證?

不要說'發佈完整的代碼' - 這不是我的知識產權,我有一個很好的理由匿名。除此之外沒有其他的東西,我用這個最小的例子進行了測試,結果相同。

+0

相關:(我不是說他們必然是錯在這種情況下)http://w3fools.com/ – JJJ

+0

謝謝 - 我還沒有發現W3School可以很好地利用我自己,但是將它作爲可能大家都聽說過的參考 - 並且您真的希望頁面上的第一句關於Xml Schema的基本片斷是正確的! –

回答

6

你需要指定minOccurs="0"每一個可選元素在xs:all

<?xml version="1.0" encoding="utf-8"?> 
<xs:schema id="inspec" 
    targetNamespace="the_right_namespace" 
    xmlns:xs="http://www.w3.org/2001/XMLSchema" 
> 
    <xs:element name="inspec"> 
     <xs:complexType> 
      <xs:all> 
       <xs:element name="a_scalar_property" type="xs:int" minOccurs="0" /> 
       <xs:element name="a_collection_property" minOccurs="0"> 
        <xs:complexType> 
         <!-- snip --> 
        </xs:complexType> 
       </xs:element> 
       <xs:element name="another_collection_property" minOccurs="0"> 
        <xs:complexType> 
         <!-- snip --> 
        </xs:complexType> 
       </xs:element> 
      </xs:all> 
     </xs:complexType> 
    </xs:element> 
</xs:schema> 
+0

謝謝。似乎我不得不打擾 - 如果我仍然必須對每個元素進行註釋,那麼''的重點是什麼?仍然可以解決這個問題。 –

+0

很高興爲您提供幫助。 'xs:all'只是解決了「以任何順序」的一部分......當你需要「任何順序」和「零個,一個或多個」時,你可能仍然會遇到歡樂。 – Filburt

2

要使元素可選,minOccurrs屬性應該爲0,即使在< all>組中也是如此。從閱讀XML模式規範中獲取它非常麻煩,但依賴w3schools不是一個好的選擇。

+0

[MSDN上的文檔](http://msdn.microsoft.com/zh-cn/library/ms256182)以同樣的方式誤導用戶:*「允許組中的元素以任何順序出現(或不出現)在包含元素中。「* – Filburt