0

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.

farid bekran
  • 2,684
  • 2
  • 16
  • 29
Fox
  • 9,384
  • 13
  • 42
  • 63
  • if you remove the space after Directory in `[XmlElement("Directory ")]` it will generate the right xml for you. – farid bekran May 03 '16 at 04:58
  • If you mean that you need to remove xml namespaces of generated xml you make take a look at this question : http://stackoverflow.com/q/2950658/1095390 – farid bekran May 03 '16 at 05:02

1 Answers1

1

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.

Hamid
  • 26
  • 3