我在类
中有一个列表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>
如何使用列表实现此目的?
答案 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;
}