嵌套对象的IList和自定义XML序列化

时间:2012-01-20 11:53:50

标签: c# .net xml-serialization ixmlserializable

我正在尝试序列化IList。所以我正在使用IXmlSerializable。课程如下

class SerializeTarget : IXmlSerializable 
{

    public IList<Target> Targets { get; set; }

    public string Name;

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }

    /// <summary>
    /// </summary>
    /// <param name="writer">
    /// The writer.
    /// </param>
    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteStartElement("SerializeTarget");
        writer.WriteElementString("Name", Name);
        writer.WriteStartElement("Targets");
        foreach (var target in Targets)
        {
            ///??????
        }
        writer.WriteEndElement();
        writer.WriteEndElement();
    }

    #endregion
}

class Target : IXmlSerializable 
{
    public String Name   { get; set; }

    #region IXmlSerializable Members

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        throw new NotImplementedException();
    }

    public void ReadXml(System.Xml.XmlReader reader)
    {
        throw new NotImplementedException();
    }

    public void WriteXml(System.Xml.XmlWriter writer)
    {
        writer.WriteString(Name);
    }

    #endregion
}

如何从SerializeTarget.Serialize?

调用嵌套对象的序列化

2 个答案:

答案 0 :(得分:1)

这似乎很容易:

 foreach (var target in Target)
 {
     ///??????
     target.WriteXml(writer);
 }

这有问题吗?

编辑:但你可能也需要Start和End元素,它们应该进入Target方法:

public void WriteXml(System.Xml.XmlWriter writer)
{
    writer.WriteStartElement("Target");
    writer.WriteString(Name);
    writer.WriteEndElement(); 
}

答案 1 :(得分:1)

如果您遵循@Henk Holterman的建议,您还希望将目标上的WriteXML更改为

writer.WriteAttributeString("Name",Name);

你也可以使用而不是WriteXml()

XmlSerializer xmlSerializer = new XmlSerializer(target.GetType());
xmlSerializer.Serialize(writer, target);

无论哪种方式都应该给你:

 <?xml version="1.0" encoding="utf-16" ?> 
<SerializeTarget>
  <Name /> 
 <Targets>
 <Target>
  <Target Name="foo" /> 
  </Target>
 <Target>
  <Target Name="foo2" /> 
  </Target>
 <Target>
  <Target Name="foo3" /> 
 </Target>
 </Targets>
</SerializeTarget>