Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize objects to xml?

How can i serialize two objects, of Class A and Class B, to xml so that it can be of the following format:

<root>
<objClassA> //Parent Node
  <objClassB> // child node of objClassA
  </objClassB>
</objClassA>
</root>
like image 297
NewBie Avatar asked Feb 10 '26 22:02

NewBie


2 Answers

[Serializable(true)]
public class objClassB
{
}

[Serializable(true)]
public class objClassA
{
    public objClassB instance;
}

Then use the XmlSerializer for an instance of objClassA and it will automatically place the instance of the b inside itself as a child.

like image 85
Phil Wright Avatar answered Feb 12 '26 16:02

Phil Wright


using System;
using System.IO;
using System.Xml.Serialization;

void Write(root rootInstance)
{
    XmlSerializer xmlSerializer = new XmlSerializer(typeof(root));
    using (FileStream fileStream = new FileStream("filepath.xml", FileMode.Create))
    {
        xmlSerializer.Serialize(fileStream, rootInstance);
    }
}

    public class root
    {
        public ClassA objClassA { get; set; }
    }

    public class ClassA
    {
        public ClassB objClassB { get; set; }
    }
    public class ClassB { }
like image 35
Jake Berger Avatar answered Feb 12 '26 16:02

Jake Berger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!