2013-01-03 3 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」型の名前をworkaroundとして「example」に変更することができます...慣習を破るために立つことができる場合... – RichardTowers

答えて

5

問題はXmlSerializerが内蔵されていることをあなたのタイプはICollectionを実装するために起こるとちょうど独自のルールに従ってそれをシリアル化するかどうか、それはすべてあなたの特性および(innerListを含む)のフィールドを無視することを意味し、コレクション型のための取り扱いです。

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

希望連載を持っています。しかし、あなたは(あなたがあなたの例で使用されていたXmlRootではなく)それはXmlType属性を持つコレクションアイテムに使用する要素の名前をカスタマイズすることができます。

http://msdn.microsoft.com/en-us/library/ms950721.aspxを参照してください。特に、「コレクションクラスのすべてのプロパティがシリアル化されないのはなぜですか?」という質問に対する答えです。

+0

あなたは正しいです!ありがとう。私は 'List'からの継承のために' ICollection'の実装を破棄しました。 '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> 

ができます。

関連する問題