在集合对象上实现IXmlSerializable

5

我有一个类似于这样的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序列化/反序列化到文件中。
问题是,当我在我的“子对象”Item上实现自定义IXmlSerializable函数时,当从文件反序列化时,我总是只得到一个项目(第一个)在XmlObject.listitems集合中。 如果我删除:IXmlSerializable,一切都按预期工作。
我做错了什么?
编辑:我已经实现了IXmlSerializable.GetSchema,并且我需要在我的“子对象”上使用IXmlSerializable来执行一些自定义值转换。
2个回答

2

请按照以下方式修改您的代码:

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

首先,跳过Item节点的开头,读取两个字符串,然后跳过结束节点,这样读者就可以到达正确的位置。这将读取数组中的所有节点。

如果你自己修改XML,请注意:)


1

你不需要使用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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接