2016-11-20 48 views
0

我從List<int>派生並希望使用自定義名稱進行XML序列化。例如:列表的命名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> 

但我想命名元素<Bar>而不是<int>。我嘗試了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