Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an xml file looking somewhat like this:

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

And I have a 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 use the XmlSerializer to serialize/deserialize the XmlObject to file.

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

What do I do wrong?

Edit: I have have implemented IXmlSerializable.GetSchema and I need to use IXmlSerializable on my "child-object" for doing some custom value transformation.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
318 views
Welcome To Ask or Share your Answers For Others

1 Answer

Modify your code like this:

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

First you skip the start of the Item node, read the two strings, then read past the end node so the reader is at the correct place. This will read all nodes in the array.

You need to pay attention when modifying xml yourself :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...