2010-06-03 46 views
1

Ia處理一封電子郵件並在xml文檔中保存一些標題。我還需要根據xml模式驗證文檔。忽略元素順序xml中的xml驗證

由於主題提示,我需要驗證忽略元素順序,但據我所知,這似乎是不可能的。我對麼?

如果我把標題放在<xsd:sequence>中,順序顯然很重要。如果我我們<xsd:all>順序被忽略,但由於一些奇怪的原因,這意味着元素必須至少出現一次。

我的XML是這樣的:

<headers> 
    <subject>bla bla bla</subject> 
    <recipient>[email protected]</recipient> 
    <recipient>rcp02domain.com</recipient> 
    <recipient>[email protected]</recipient> 
</headers> 

,但我認爲最終的文件是有效的,即使主題和收件人元素交換。

有沒有什麼可做的?

回答

4

是的,這是可能的。只要創建一個選項(當然在某些類型或元素內容模型中),maxOccurs設置爲無界。

<xs:element name="headers"> 
    <xs:complexType> 
     <xs:choice maxOccurs="unbounded"> 
      <xs:element name="subject" type="xs:string"/> 
      <xs:element name="recipient" type="xs:string"/> 
     </xs:choice> 
    </xs:complexType> 
</xs:element> 
+0

@segolas,我可以看到此解決方案符合您的要求,請展示禮貌接受解決方案。 – 2010-06-07 07:17:28

+0

我正在研究Netbeans,並且使用這個解決方案給了我一些我想弄明白的錯誤。所以,現在我不知道這個答案是否有效! – Segolas 2010-06-07 10:45:42

+1

嗯...我認爲它的工作,但現在jaxb生成一個方法getSubjectOrRecipient()而不是getSubject()和getRecipient()。 根據http://www.w3schools.com/Schema/el_choice.asp「XML Schema選擇元素只允許包含在聲明中的元素中的一個出現在包含元素中。」 所以,似乎我只能在標題元素內有主題或收件人......我是對嗎? – Segolas 2010-06-07 14:00:39

0

首先,一些要求猜測:

  • 「主題」 是強制性
  • 至少有一個 「收件人」 是強制性

因爲你只有兩種不同的元素是很容易實現它:

<xs:element name="headers"> 
<xs:complexType> 
<xs:choice> 
    <xs:sequence><!-- The recipient MUST be after the subject -->   
    <xs:element name="subject" type="xs:string" /> 
    <xs:element name="recipient" minOccurs="1" maxOccurs="unbound" type="xs:string" /> 
    </xs:sequence> 
    <xs:sequence><!-- The recipient is before the subject -->   
    <xs:element name="recipient" minOccurs="1" maxOccurs="unbound" type="xs:string" /> 
    <xs:element name="subject" type="xs:string" /> 
    <xs:element name="recipient" minOccurs="0" maxOccurs="unbound" type="xs:string" /> 
    </xs:sequence> 
</xs:choice> 
</xs:complexType> 
</xs:element> 
+0

不幸的是我只發佈了一個我的xml的例子,實際上我有很多元素。我理解你的解決方案,但我認爲會使我的模式不易讀,並且難以維護... – Segolas 2010-06-07 13:39:53