![](/img/trans.png)
[英]Deserializing collection of types implementing IXmlSerializable runs forever
[英]Implementing IXmlSerializable on a collection object
我有一個看起來像這樣的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進行一些自定義值轉換。
像這樣修改你的代碼:
public void ReadXml(System.Xml.XmlReader reader)
{
reader.Read();
this.C = reader.ReadElementString();
this.D = reader.ReadElementString();
reader.Read();
}
首先,您跳過Item節點的開頭,讀取兩個字符串,然后讀取結束節點,以便讀取器位於正確的位置。 這將讀取數組中的所有節點。
你自己修改xml時需要注意:)
您不需要使用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
}
itemlist中的2個項目的結果將如下所示:
<?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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.