Fox
Fox

Reputation: 9444

Serialize same object type at multiple levels

I am looking for an XML Structure like this -

<Directory id="ID1" Name="N1">
   <Directory id="ID2" Name="N2">
      <Directory id="ID3" Name="N3">
         <Directory id="ID4" Name="N4"/>
      </Directory>
   </Directory>
</Directory>

I wrote a class -

namespace Application1
{
   public class Directory
   {
      [XmlAttribute]
      public string Id { get; set; }
      [XmlAttribute]
      public string Name { get; set; }
      [XmlElement("Directory ")]
      public Dir[] Directory { get; set; }
   }
}

But this does not generate the XML in the form I wanted.

Upvotes: 0

Views: 556

Answers (1)

Hamid
Hamid

Reputation: 26

general XML serializer which comes with .net framework is XmlSerializer. all you need to do is serialize the root object and write the serialized content to XDocument for futhur usage.

add [Serializable] attribute for you class declaration:

[Serializable] public class Directory { [XmlAttribute] public string Id { get; set; } [XmlAttribute] public string Name { get; set; } [XmlElement("Directory")] public Directory[] Directories { get; set; } }

and then use the following codes:

XmlSerializer serializer = new XmlSerializer(typeof(Directory));
XDocument doc = new XDocument();
using (var writer = doc.CreateWriter())
{
      serializer.Serialize(writer, rootDir);
}

NOTE: if any reference cycle happens in any level of your tree, serialization crashes.

Upvotes: 1

Related Questions