将XML属性注入序列化

时间:2009-08-05 15:54:43

标签: c# xml-serialization

我正在尝试序列化一个数组,并希望将一个属性附加到该数组。例如,我想要的输出是:

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

这只是一个原始数组,所以我不想为数组本身定义属性,只是在它的序列化中。有没有办法将属性注入序列化?

2 个答案:

答案 0 :(得分: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());
    }

答案 1 :(得分:0)

有点黑客将数组序列化为XML,然后在保存之前修改序列化的XML。假设Array是类的属性的更简洁方法是Add an attribute to a serialized XML node