2013-12-20 47 views
5

我有一個非常奇怪的情況。我連載我的命名空間是這樣的:c#XML序列化:命名空間聲明的順序

var namespaces = new XmlSerializerNamespaces(); 
namespaces.Add("xsd", "http://www.w3.org/2001/XMLSchema"); 
namespaces.Add("xsi", "http://www.w3.org/2001/XMLSchema-instance"); 

serializer.Serialize(writer, config, namespaces); 

在我的機器,我得到下面的XML(一行我只是說換行):

<SystemConfiguration 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns="http://www.schaeffler.com/sara/systemconfiguration/"> 

在buildserver我用同樣的軟件此獲得:

<SystemConfiguration 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
     xmlns="http://www.schaeffler.com/sara/systemconfiguration/"> 

您看到xsd和xsi的順序被交換。我檢查了序列化器的實現,並看到該序列由散列表確定,並且沒有XmlSerializerNamespaces接口來實現我自己的命名空間序列化程序。

這是XmlSerializationWriter方法:

protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) 
    { 
     if (xmlns != null) 
     { 
     foreach (DictionaryEntry dictionaryEntry in xmlns.Namespaces) 
     { 
      string localName = (string) dictionaryEntry.Key; 
      string ns = (string) dictionaryEntry.Value; 
      if (this.namespaces != null) 
      { 
      string str = this.namespaces.Namespaces[(object) localName] as string; 
      if (str != null && str != ns) 
       throw new InvalidOperationException(Res.GetString("XmlDuplicateNs", (object) localName, (object) ns)); 
      } 
      string str1 = ns == null || ns.Length == 0 ? (string) null : this.Writer.LookupPrefix(ns); 
      if (str1 == null || str1 != localName) 
      this.WriteAttribute("xmlns", localName, (string) null, ns); 
     } 
     } 
     this.namespaces = (XmlSerializerNamespaces) null; 
    } 

什麼能導致不同的順序散列映射內的命名空間?

回答

3

從MSDN:

的元件根據所述密鑰的散列值進行排序,並且每個 可以鍵集合中只存在一次。

DictionaryEntry爲散列值(一個struct)從ValueType.GetHashCode()萃取。它很可能會返回一個不可確定的密鑰 - 可能基於潛在的參考值。你需要做一些進一步的反思,以確定散列是如何計算的。它可能只是使用默認的object實現。

從MSDN

另外:

的哈希代碼是用於高效地插入和查找在是基於哈希表 集合。散列碼不是 永久值。