2016-11-20 7 views
0

List<int>から派生し、カスタム名でXMLシリライズしたいと思います。例:Listの名前付きXMLシリアル化

using System; 
using System.Collections.Generic; 
using System.Xml.Serialization; 
using System.IO; 
namespace xmlerror 
{ 
    [Serializable, XmlRoot("Foo")] 
    public class Foo : List<int> 
    { 
    } 

    class MainClass 
    { 
     public static void Main(string[] args) 
     { 
      var foo = new Foo(); 
      foo.Add(123); 

      using (var writer = new StringWriter()) 
      { 
       var serilizer = new XmlSerializer(typeof(Foo)); 
       serilizer.Serialize(writer, foo); 
       Console.WriteLine(writer.ToString()); 
      }    
     } 
    } 
} 

出力:

<?xml version="1.0" encoding="utf-16"?> 
<Foo xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
    <int>123</int> 
</Foo> 

しかし、私は要素の代わりに<int><Bar>を名前を付けたいです。私はXML属性XmlAnyElementXmlArrayItemを試しましたが、終わりはありません。要素タグの名前を変更するにはどうすればよいですか? XmlTextWriterで手動で行う必要がありますか?

答えて

1

これを行う方法は数多くあります。

たとえば、IXmlSerializableインターフェイスを実装できます。

[XmlRoot("Foo")] 
public class Foo : List<int>, IXmlSerializable 
{ 
    public XmlSchema GetSchema() 
    { 
     throw new NotImplementedException(); 
    } 

    public void ReadXml(XmlReader reader) 
    { 
     reader.ReadToFollowing("Bar"); 

     while (reader.Name == "Bar") 
      this.Add(reader.ReadElementContentAsInt()); 
    } 

    public void WriteXml(XmlWriter writer) 
    { 
     foreach (var n in this) 
      writer.WriteElementString("Bar", n.ToString()); 
    } 
} 
1

int以外のものを使用する最も明白な解決策です。

public class Bar 
{ 
    public Bar(int value) 
    { 
     Value = value; 
    } 

    public Bar() 
    { 

    } 

    [XmlText] 
    public int Value { get; set; } 
} 

public class Foo : List<Bar> 
{ 

} 

作業デモについては、this fiddleを参照してください。

脇に、Serializable属性はXmlSerializerとは関係がなく、省略することができます。

+0

これも機能しますが、私は他の答えを使用することに決めました。 – aggsol