Embedding IXmlSerializable in a Collection Object

I have an xml file that looks something like this:

<xml>
  <A>value</A>
  <B>value</B>
  <listitems>
    <item>
      <C>value</C>
      <D>value</D> 
    </item>
  </listitems>
</xml>

And I have two objects representing this 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);
  }
}

I am using XmlSerializer to serialize / deserialize an XmlObject file to a file.

The problem is that when I implemented the IXmlSerializable custom functions in the sub-object element, I always get only one element (the first) in my XmlObject.listitems collection when deserializing the file. If I remove: IXmlSerializable, everything works as expected.

What am I doing wrong?

Edit: I have implemented IXmlSerializable.GetSchema, and I need to use IXmlSerializable for my "child" to perform a specific custom value conversion.

+5
2

:

    public void ReadXml(System.Xml.XmlReader reader)
    {
        reader.Read();
        this.C = reader.ReadElementString();
        this.D = reader.ReadElementString();
        reader.Read();
    }

node, , node, . .

xml :)

+2

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
}

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>
+1

All Articles