实现IXmlSerializable的集合对象 [英] Implementing IXmlSerializable on a collection object

查看:429
本文介绍了实现IXmlSerializable的集合对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个xml文件看有点像这样的:

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>

和我有表示此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);
  }
}



我用XmlSerializer的序列化/反序列化的XmlObject到文件。

I use the XmlSerializer to serialize/deserialize the XmlObject to file.

的问题是,当我实现我的子对象项目自定义的IXmlSerializable功能,我永远只能在我的XmlObject获取一个项目(第一批)。反序列化文件时ListItems的集合。
如果我删除了。?的IXmlSerializable一切正常

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.

我该怎么办错了

编辑:我也已经实现IXmlSerializable.GetSchema,我需要用我的IXmlSerializable子对象做一些自定义的值转换上

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

推荐答案

修改你的代码是这样的:

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.

您需要修改XML自己,当要注意:)

You need to pay attention when modifying xml yourself :)

这篇关于实现IXmlSerializable的集合对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆