2009-08-26 73 views
9

鑑於這種XML模式(片段):序列模式元素是否保證子元素的順序?

<xs:element name="GetIEnumerableResponse"> 
    <xs:complexType> 
    <xs:sequence> 
     <xs:element minOccurs="0" name="GetIEnumerableResult" nillable="true" xmlns:q4="http://schemas.microsoft.com/2003/10/Serialization/Arrays" type="q4:ArrayOfstring" /> 
    </xs:sequence> 
    </xs:complexType> 
</xs:element> 

在該XML片段:

<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
    <string>string1</string> 
    <string>string2</string> 
    <string>string3</string> 
</ArrayOfstring> 

可以在<串> < /串>元件以任何順序出現?因此,是XML的這些兩個片段語義等同放着清單:

<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
    <string>string1</string> 
    <string>string2</string> 
    <string>string3</string> 
</ArrayOfstring> 

<ArrayOfstring xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
    <string>string3</string> 
    <string>string2</string> 
    <string>string1</string> 
</ArrayOfstring> 

抑或架構中的序列元件意味着<串> < /串>元件具有以相同的順序是語義上等同於發生?

模式中的存在是否需要解析器/反序列化器使元素保持其在xml文本中存在的順序?如果我理解正確,通常(即沒有模式)不需要這樣做(即使大多數解析器通常都這樣做)。

回答

7

Sequence元素表示單個元素(不是數組中的元素)應該保持順序。

例如

<xs:element name="GetIEnumerableResponse"> 
    <xs:complexType> 
    <xs:sequence> 
     <xs:element minOccurs="0" name="GetIEnumerableResult" nillable="true" xmlns:q4="http://schemas.microsoft.com/2003/10/Serialization/Arrays" type="q4:ArrayOfstring" /> 
     <xs:element name="Dummy" type="xs:string" /> 
    </xs:sequence> 
    </xs:complexType> 
</xs:element>  

在此示例中,虛擬GetIEnumerableResult後出現的序列中,並驗證它應該永遠出現在此複雜類型的順序。

「ArrayOfString」複雜類型中「重複」項目的順序在模式中不可強制執行,並且因爲數組不會暗示或強制執行任何顯式順序,所以在CLR中也不保證順序的語義。

確保訂單的一種方法是通過序列化索引對集合施加順序。

+1

優秀的答案,序列化索引確實是我使用的原始解決方案。我創建了一個「OrderedList 」類,該類基本上是一個字典,其中int是索引。顯然這是正確的答案。 – Mark 2009-08-26 18:13:05

1

這真的取決於上下文。在XML最純粹的形式中,無論順序如何,您提供的片段在語義上都是等效的。但是,當你用XML來序列化事物時,可能會有與元素順序相關的含義。

在這種情況下,當且僅當結果數組在語義上相同時,XML文檔在語義上是等價的。

+2

對,這是問題。模式中的存在是否需要解析器/反序列化器將元素保存爲xml文本中存在的順序?如果我理解正確,通常(即沒有模式)不需要這樣做(即使大多數解析器通常都這樣做)。 – Mark 2009-08-26 17:37:45

+0

據我所知,模式對元素的讀取沒有任何影響。相反,它只是一種在閱讀文檔時瞭解文檔是否有效的方法。 – Welbog 2009-08-26 17:41:44

2

字符串元素可以以任何順序出現 - 因爲對他們的模式都是一樣的

相關問題