2015-05-25 33 views
0

我試圖序列化一個類到XML,我無法得到我想要的屬性只是一個列表的子元素的結果。 (C#,.Net4.5中的WinForms努力)爲列表命名<T>元素用於XML序列化

我的例子如下:

[Serializable] 
public class Model 
{ 
    public string element = "elTest"; 
    public List<String> roles; 
} 

其中我寫出來,以XML

private void button2_Click(object sender, EventArgs e) 
    { 
     var me = new Model(); 
     me.roles = new List<string>() 
     { 
      "testString" 
     }; 
     var ser = new XmlSerializer(typeof(OtherModel)); 
     using (var sw = new StreamWriter("C:\\temp\\test123.xml")) 
     { 
      ser.Serialize(sw, me); 
     } 
    } 

這一點讓我喜歡的輸出:

<element>elTest</element> 
    <roles> 
    <string>testString</string> 
    </roles> 

我如何得到它,以便

<string> 
在這個例子中

顯示爲

<role> 

我試圖創建另一個類角色白衣自己的財產,使一個名單,但後來我得到類似

<roles> 
    <Role> 
     <myRole>theRole</myRole> 

其中ISN我想要什麼。

謝謝。

+0

你不需要兩層角色和角色。而不是使用XmlArray使用XmlElement。 – jdweng

回答

3

需要使用屬性XmlArrayItem

https://msdn.microsoft.com/en-us/library/vstudio/2baksw0z(v=vs.100).aspx

[Serializable] 
public class Model 
    { 
     public string element = "elTest"; 
     [XmlArrayItem("role")] 
     public List<String> roles; 
    } 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var me = new Model(); 
      me.roles = new List<string>() 
     { 
      "testString" 
     }; 
      var ser = new XmlSerializer(me.GetType()); 
      using (var sw = new StreamWriter("0.xml")) 
      { 
       ser.Serialize(sw, me); 
      } 

      Console.ReadKey(true); 
     } 
} 

另存爲:

<?xml version="1.0" encoding="utf-8"?> 
<Model xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <element>elTest</element> 
    <roles> 
    <role>testString</role> 
    </roles> 
</Model> 
0

究竟XmlArrayItem解決您的問題。