2009-08-05 42 views
2

我想序列化一個數組並想將一個屬性附加到數組中。例如,我想輸出是:將XML屬性注入到序列化中

<ArrayOfThingie version="1.0"> 
    <Thingie> 
    <name>one</name> 
    </Thingie> 
    <Thingie> 
    <name>two</name> 
    </Thingie> 
</ArrayOfThingie> 

這僅僅是一個基本類型數組,所以我不想定義數組本身的屬性,只是在它的序列化。有沒有辦法將一個屬性注入到序列化中?

回答

2

你可以只爲序列化創造ArrayOfThingie的包裝:

public class Thingie 
    { 
     [XmlElement("name")] 
     public string Name { get; set; } 
    } 

    [XmlRoot] 
    public class ArrayOfThingie 
    { 
     [XmlAttribute("version")] 
     public string Version { get; set; } 
     [XmlElement("Thingie")] 
     public Thingie[] Thingies { get; set; } 
    } 

    static void Main(string[] args) 
    { 
     Thingie[] thingies = new[] { new Thingie { Name = "one" }, new Thingie { Name = "two" } }; 

     ArrayOfThingie at = new ArrayOfThingie { Thingies = thingies, Version = "1.0" }; 
     XmlSerializer serializer = new XmlSerializer(typeof(ArrayOfThingie)); 
     StringWriter writer = new StringWriter(); 
     serializer.Serialize(writer, at); 

     Console.WriteLine(writer.ToString()); 
    } 
+0

尼斯。我一直在尋找XmlSerializer命名空間的工作。這有很多方法可以完成我想要的,但並不完全。這很簡單。謝謝! – Jerry 2009-08-05 17:12:58