我想序列化和反序列化这样的对象:
public class Root
{
public string title;
[XmlArray("lista")]
[XmlArrayItem("Parameter")]
public List<Parameter> lista;
}
public class Parameter : IXmlSerializable
{
public string name;
public int val;
public void WriteXml(XmlWriter writer)
{
writer.WriteElementString("name",name);
writer.WriteElementString("val",val.ToString());
}
public void ReadXml(XmlReader reader)
{
reader.ReadToDescendant("name");
name = reader.ReadElementContentAsString();
val = reader.ReadElementContentAsInt();
}
public XmlSchema GetSchema()
{
return (null);
}
}
问题是当我反序列化这个对象时,它只添加列表的第一个元素.例:
序列化:
<Root>
<title>title</title>
<lista>
<Parameter>
<name>pa</name>
<val>1</val>
</Parameter>
<Parameter>
<name>pb</name>
<val>2</val>
</Parameter>
</lista>
</Root>
反序列化:
<Root>
<title>title</title>
<lista>
<Parameter>
<name>pa</name>
<val>1</val>
</Parameter>
</lista>
</Root>
我已经实现了一个Fiddle的例子.
有人能帮助我吗?
解决方法:
你只是在阅读你要添加的第一个元素reader.Read();在RealXml方法结束时创建一个循环:
public void ReadXml(XmlReader reader)
{
reader.ReadToDescendant("name");
name = reader.ReadElementContentAsString();
val = reader.ReadElementContentAsInt();
reader.Read();
}
但是如果没有特定的原因,则不需要实现IXmlSerializable.
你可以简单地使用XmlSerializer如下:
XmlSerializer serializer = new XmlSerializer(typeof(Root));
StringBuilder result = new StringBuilder();
using (var writer = XmlWriter.Create(result))
{
serializer.Serialize(writer, root); /// serialize
}
using (var reader = new StringReader(result.ToString()))
{
var deserialized = (Root)serializer.Deserialize(reader); //// deserialize from string
}