IList and custom XML Serialization of nested objects

2.1k views Asked by At

I am trying to serialize IList. So I am using IXmlSerializable for this. The classes are as follows

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
}

How can I call the serialize of the nested object from SerializeTarget.Serialize?

2

There are 2 answers

0
Richard Hanley On BEST ANSWER

If you follow @Henk Holterman advice you also want to change the WriteXML on target to be

writer.WriteAttributeString("Name",Name);

you can also use instead of WriteXml()

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

Either way should give you:

 <?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>
0
Henk Holterman On

That seems very easy:

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

Is there a problem with that?

Edit: But you will probably need Start and End elements too, they ought to go inside the Target method:

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