2013-01-03 18 views
6

我需要導出駱駝套管中的項目集合,爲此我使用包裝器。XMLSerializer將大寫項目保留在集合中

類本身:

[XmlRoot("example")] 
public class Example 
{ 
    [XmlElement("exampleText")] 
    public string ExampleText { get; set; } 
} 

這連載罰款:

<example> 
    <exampleText>Some text</exampleText> 
</example> 

的包裝:

[XmlRoot("examples")] 
public class ExampleWrapper : ICollection<Example> 
{ 
    [XmlElement("example")] 
    public List<Example> innerList; 

    //Implementation of ICollection using innerList 
} 

然而,這大寫的包裹Example S代表某種原因,我試着用XmlElement覆蓋它,但是這似乎沒有期望的效果ct:

<examples> 
    <Example> 
     <exampleText>Some text</exampleText> 
    </Example> 
    <Example> 
     <exampleText>Another text</exampleText> 
    </Example> 
</examples> 

誰能告訴我我做錯了什麼,或者是否有更簡單的方法?

+0

您可以隨時將'Example'類型重命名爲'example'作爲工作區...如果您可以站出來打破慣例...... – RichardTowers

回答

5

的問題是,XmlSerializer內置了處理的集合類型,這意味着,如果你的類型恰好實現ICollection,並根據自己的規則將只序列化它,它會忽略所有的屬性和字段(包括innerList)。但是,您可以自定義元素的它用來與XmlType屬性的集合項目(而不是你已經在你的例子中使用的XmlRoot)名稱:

[XmlType("example")] 
public class Example 
{ 
    [XmlElement("exampleText")] 
    public string ExampleText { get; set; } 
} 

這將具有所需的序列化。

請參閱http://msdn.microsoft.com/en-us/library/ms950721.aspx,特別是對「爲什麼並非集合類的所有屬性都序列化?」這個問題的回答。

+0

您是正確的先生!謝謝。我放棄了'ICollection'的實現,以支持從'List'繼承。看起來'XmlRoot'不是必需的,對嗎? – siebz0r

+0

更正,如果你使用它作爲序列化對象圖的根,''XmlRoot'只會在'Example'中需要。 – luksan

0

不幸的是,你不能僅僅使用屬性來實現這一點。您還需要使用屬性覆蓋。使用上面的類,我可以使用XmlTypeAttribute覆蓋該類的字符串表示形式。

var wrapper = new ExampleWrapper(); 
var textes = new[] { "Hello, Curtis", "Good-bye, Curtis" }; 
foreach(var s in textes) 
{ 
    wrapper.Add(new Example { ExampleText = s }); 
} 

XmlAttributeOverrides overrides = new XmlAttributeOverrides(); 
XmlAttributes attributes = new XmlAttributes(); 
XmlTypeAttribute typeAttr = new XmlTypeAttribute(); 
typeAttr.TypeName = "example"; 
attributes.XmlType = typeAttr; 
overrides.Add(typeof(Example), attributes); 

XmlSerializer serializer = new XmlSerializer(typeof(ExampleWrapper), overrides); 
using(System.IO.StringWriter writer = new System.IO.StringWriter()) 
{ 
    serializer.Serialize(writer, wrapper); 
    Console.WriteLine(writer.GetStringBuilder().ToString()); 
} 

這給

<examples> 
    <example> 
    <exampleText>Hello, Curtis</exampleText> 
    </example> 
    <example> 
    <exampleText>Good-bye, Curtis</exampleText> 
    </example> 
</examples> 

,我相信你想要的。