2008-09-24 179 views
22

我發現了一個問題,C#的XML序列化。串行化器的輸出是正常的Win32和WinCE(但令人驚訝的WinCE具有IMO correcter輸出)之間不一致。 Win32的根本忽略了Class2中XmlRoot("c2")屬性。C#陣列XML序列化

有誰知道路怎麼走在WinCE像在Win32輸出(因爲我不希望XML標記有序列化類的類名)。

測試代碼:

using System; 
using System.Xml.Serialization; 
using System.IO; 

namespace ConsoleTest 
{ 
    [Serializable] 
    [XmlRoot("c1")] 
    public class Class1 
    { 
     [XmlArray("items")] 
     public Class2[] Items; 
    } 

    [Serializable] 
    [XmlRoot("c2")] 
    public class Class2 
    { 
     [XmlAttribute("name")] 
     public string Name; 
    } 

    class SerTest 
    { 
     public void Execute() 
     { 
      XmlSerializer ser = new XmlSerializer(typeof (Class1)); 

      Class1 test = new Class1 {Items = new [] {new Class2 {Name = "Some Name"}, new Class2 {Name = "Another Name"}}}; 

      using (TextWriter writer = new StreamWriter("test.xml")) 
      { 
       ser.Serialize(writer, test); 
      } 
     } 
    } 
} 

預期的XML(WinCE的生成此):

<?xml version="1.0" encoding="utf-8"?> 
<c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <items> 
    <c2 name="Some Name" /> 
    <c2 name="Another Name" /> 
    </items> 
</c1> 

的Win32 XML(似乎是錯誤的版本):

<?xml version="1.0" encoding="utf-8"?> 
<c1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <items> 
    <Class2 name="Some Name" /> 
    <Class2 name="Another Name" /> 
    </items> 
</c1> 

回答

35

嘗試[XmlArrayItem ( 「C2」)]

[XmlRoot("c1")] 
public class Class1 
{ 
    [XmlArray("items")] 
    [XmlArrayItem("c2")] 
    public Class2[] Items; 
} 

或[XmlType將( 「C2」)]

[XmlType("c2")] 
public class Class2 
{ 
    [XmlAttribute("name")] 
    public string Name; 
}