我有一个xml文件,看起来有点像这样:
<xml>
<A>value</A>
<B>value</B>
<listitems>
<item>
<C>value</C>
<D>value</D>
</item>
</listitems>
</xml>我有两个对象表示这个xml:
class XmlObject
{
public string A { get; set; }
public string B { get; set; }
List<Item> listitems { get; set; }
}
class Item : IXmlSerializable
{
public string C { get; set; }
public string D { get; set; }
//Implemented IXmlSerializeable read/write
public void ReadXml(System.Xml.XmlReader reader)
{
this.C = reader.ReadElementString();
this.D = reader.ReadElementString();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("C", this.C);
writer.WriteElementString("D", this.D);
}
}我使用XmlSerializer将XmlObject序列化/反序列化到文件中。
问题是,当我在“子对象”项上实现自定义IXmlSerializable函数时,在反序列化文件时,我总是只在XmlObject.listitems集合中获得一项(第一项)。如果我删除: IXmlSerializable,一切都会正常工作。
我做错了什么?
编辑:我已经实现了IXmlSerializable.GetSchema,我需要在我的“子对象”上使用IXmlSerializable来做一些定制值转换。
发布于 2009-09-06 14:33:35
像这样修改你的代码:
public void ReadXml(System.Xml.XmlReader reader)
{
reader.Read();
this.C = reader.ReadElementString();
this.D = reader.ReadElementString();
reader.Read();
}首先,您跳过项目节点的开始,读取两个字符串,然后读取结束节点,以便阅读器位于正确的位置。这将读取数组中的所有节点。
您自己修改xml时需要注意:)
发布于 2009-09-06 11:41:16
您不需要使用IXmlSerializable。但是如果你愿意,你应该实现GetShema()方法。经过一些修改后,可以工作的代码如下所示:
[XmlRoot("XmlObject")]
public class XmlObject
{
[XmlElement("A")]
public string A { get; set; }
[XmlElement("B")]
public string B { get; set; }
[XmlElement("listitems")]
public List<Item> listitems { get; set; }
}
public class Item : IXmlSerializable
{
[XmlElement("C")]
public string C { get; set; }
[XmlElement("D")]
public string D { get; set; }
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(System.Xml.XmlReader reader)
{
this.C = reader.ReadElementString();
this.D = reader.ReadElementString();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteElementString("C", this.C);
writer.WriteElementString("D", this.D);
}
#endregion
}项目列表中两个项目的结果将如下所示:
<?xml version="1.0" encoding="utf-8"?>
<XmlObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<A>value</A>
<B>value</B>
<listitems>
<C>value0</C>
<D>value0</D>
</listitems>
<listitems>
<C>value1</C>
<D>value1</D>
</listitems>
</XmlObject>https://stackoverflow.com/questions/1385382
复制相似问题