0

我有一个像这样的班级名单

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>

我如何使用列表来实现这一点?

4

1 回答 1

2

将 XmlElement 属性添加到sensorListRoot 中的属性可为您提供所需的结果。检查下面的代码。

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;
}
于 2013-01-01T05:36:22.833 回答