如何以格式化方式序列化列表

时间:2013-01-01 05:05:17

标签: c# serialization

我在类

中有一个列表
public class Root
{
 public List<Sensor> sensorList
 {
    get;set;
 }
}

序列化此类时,XML就像这样

<?xml version="1.0" encoding="us-ascii"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <sensorList>
    <Sensor>
      <Channel>1</Channel>
    </Sensor>
    <Sensor>
      <Channel>2</Channel>
    </Sensor>
  </sensorList>
</Root>

但我需要像这样的xml

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
    <Sensor>
      <Channel>1</Channel>
    </Sensor>
    <Sensor>
      <Channel>2</Channel>
    </Sensor>  
</Root>

如何使用列表实现此目的?

1 个答案:

答案 0 :(得分:2)

在Root中的sensorList属性中添加Xml元素属性可以获得所需的结果。检查下面的代码。

class Program
{
    static void Main(String[] args)
    {
        Root temp = new Root();
        temp.sensorList = new List<Sensor>();
        temp.sensorList.Add(new Sensor() { Channel = "1"});
        temp.sensorList.Add(new Sensor() { Channel = "2" });

        XmlSerializer ser = new XmlSerializer(typeof(Root));
        XDocument mydoc = new XDocument();
        using (XmlWriter writer = mydoc.CreateWriter())
        {
            ser.Serialize(writer, temp);
        }

        Console.WriteLine(" After serialize :" + mydoc.ToString());

        using (XmlReader reader = mydoc.CreateReader())
        {
            Root newTemp = (Root)ser.Deserialize(reader);
            Console.WriteLine("After deserialize :" + newTemp.sensorList.Count);
        }
    }
}

public class Root
{
    [XmlElement(ElementName="Sensor")]
    public List<Sensor> sensorList
    {
        get;
        set;
    }
}


public class Sensor
{
    public string Channel;
}