Generate XML From Object in C#

Problem Statement

Extensible Markup Language (XML) was designed to transport data and also can be used to store the data.

How to create XML from an existing object? The objects may be anything; it may be a class, collection or scalar value.

Suppose I have a collection of customer classes and I want to create an equivalent XML.

Class Definition

public class Customer
{
    public int CustomerId { get; set; }
    public string CustomerName { get; set; }
    public string PhoneNumber { get; set; }
    public string Email { get; set; }
}

The following is a function to generate some test data.

public class Utility
{
    public List<Customer> GetCustomerList()
    {

        List<Customer> customers = new List<Customer>();
        customers.Add(new Customer { CustomerId = 1, CustomerName = "Tejas Trivedi", PhoneNumber = "23244556", Email = "[email protected]" });
        customers.Add(new Customer { CustomerId = 2, CustomerName = "Jignesh Trivedi", PhoneNumber = "4545453322", Email = "[email protected]" });
        customers.Add(new Customer { CustomerId = 3, CustomerName = "Rakesh Trivedi", PhoneNumber = "333222111", Email = "[email protected]" });
        customers.Add(new Customer { CustomerId = 4, CustomerName = "Keyur Joshi", PhoneNumber = "999888822", Email = "[email protected]" });
        customers.Add(new Customer { CustomerId = 5, CustomerName = "Sachin shah", PhoneNumber = "38888232", Email = "[email protected]" });
        customers.Add(new Customer { CustomerId = 6, CustomerName = "Mandar Bhatt", PhoneNumber = "343412212", Email = "[email protected]" });
        return customers;
    }
}

Solution

There are many ways to create a XML form object. In this article I will explain them one by one.

1. Using LINQ

We can pass the contents of the element or attribute as arguments to the constructor of XElement and XAttribute. Using this constructor and a LINQ query we can create XML for any object.

Example Code

Utility utility = new Utility();
var customerlist = utility.GetCustomerList();
var xmlfromLINQ = new XElement("customers",
            from c in customerlist
            select new XElement("customer",
                new XElement("CustomerId", c.CustomerId),
                new XElement("CustomerName", c.CustomerName),
                new XElement("PhoneNumber", c.PhoneNumber),
                new XElement("Email", c.Email)
                ));

Output

<customers>
<customer>
<CustomerId>1</CustomerId>
<CustomerName>Tejas Trivedi</CustomerName>
<PhoneNumber>23244556</PhoneNumber>
<Email>[email protected]</Email>
</customer>
……
……
……
<customer>
<CustomerId>6</CustomerId>
<CustomerName>Mandar Bhatt</CustomerName>
<PhoneNumber>343412212</PhoneNumber>
<Email>[email protected]</Email>
</customer>
</customers>

2. Using XML serialization

XmlSerializer is a class that enables us to control how objects are encoded into XML. There is one drawback to the use this method; our class must be marked as a "Serializable".

Serializable

Example Code

Utility utility = new Utility();
var customerlist = utility.GetCustomerList();
 
XmlSerializer serializer = new XmlSerializer(typeof(List<Customer>));
using (TextWriter writer = new StreamWriter(@"C:\test.xml"))
{
    serializer.Serialize(writer, customerlist);
}

3. Using Data Contract serialization

The DataContractSerializer Class enables us to create a XML stream or document using the supplied data contract. Here we must mark our class as “DataContact” and the properties and fields to be serialized must be marked as a "DataMember".

DataMember

Example Code

Utility utility = new Utility();
var customerlist = utility.GetCustomerList();
 
DataContractSerializer serializer = new DataContractSerializer(typeof(List<Customer>));
using (FileStream writer = new FileStream(@"C:\test.xml", FileMode.Create))
{
    serializer.WriteObject(writer, customerlist);
}

4. Using XML Write

The XmlWriter class writes XML data to the file, steam, text reader or string. It guarantees that the XML document is well-formed.

Example Code

XmlWriterSettings setting = new XmlWriterSettings();
setting.ConformanceLevel = ConformanceLevel.Auto;
 
using (XmlWriter writer = XmlWriter.Create(@"C:\test.xml", setting))
{
    writer.WriteStartElement("customers");
    foreach (var cust in customerlist)
    {
        writer.WriteStartElement("customer");
        writer.WriteElementString("CustomerId", cust.CustomerId.ToString());
        writer.WriteElementString("CustomerName", cust.CustomerName);
        writer.WriteElementString("PhoneNumber", cust.PhoneNumber);
        writer.WriteElementString("Email", cust.Email);
        writer.WriteEndElement();
    }
    writer.WriteEndElement();
    writer.Flush();
}

5. Using XML document

XML can be generated using the XMLDocument class using the following code.

Example code

XmlDocument xml = new XmlDocument();
XmlElement root = xml.CreateElement("customers");
xml.AppendChild(root);
foreach (var cust in customerlist)
{
    XmlElement child = xml.CreateElement("customer");
    child.SetAttribute("CustomerId", cust.CustomerId.ToString());
    child.SetAttribute("CustomerName", cust.CustomerName);
    child.SetAttribute("PhoneNumber", cust.PhoneNumber);
    child.SetAttribute("Email", cust.Email);
    root.AppendChild(child);
}
string s = xml.OuterXml;

Conclusion

Using the  methods described here we can generate XML from an object in C#.

Up Next
    Ebook Download
    View all
    Learn
    View all