Geeks With Blogs

News
Joe Mayo

A lot of examples on LINQ to XML show how to translate from XML into objects. Especially with REST data sources, it seems like a lot of LINQ to XML is used to read XML.  However, there is also a need to translate from objects to XML, which isn't always as intuitive.  The following example shows a couple different ways to translate from objects to XML. It starts with a string for the XML document. There is also a List of Customer objects. This example translates the objects into XElement's and then uses the LINQ to XML Add operator to populate the XML document with those new XElement representations of the objects.  I also provided a stand-alone example that shows you how to take a single object, translate it into XML and then add that to the XML document. The example is minimal in that it has single customer elements within a customers root element. However, if you had a more complex document, you would use an XML Operator to locate an element in a document and then add from that axis. Here's the example code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
 
namespace ConsoleTest
{
    class Customer
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
 
    class Program
    {
        static void Main()
        {
            string sourceXml = @"
<customers>
    <customer>
        <id>1</id>
        <name>Manuel</name>
    </customer>
    <customer>
        <id>2</id>
        <name>Joe</name>
    </customer>
</customers>";
 
            var custList = new List
            {
                new Customer { ID = 3, Name = "Jose" },
                new Customer { ID = 4, Name = "Maria" }
            };
 
            var custXmlList =
                (from cust in custList
                 select
                    new XElement("customer",
                        new XElement("id", cust.ID),
                        new XElement("name", cust.Name)))
                 .ToList();
 
            var customers = XElement.Parse(sourceXml);
 
            custXmlList.ForEach(cust => customers.Add(cust));
 
            var anotherCust =
                new XElement("customer",
                    new XElement("id", -99),
                    new XElement("name", "{unbound}"));
 
            customers.Add(anotherCust);
 
            Console.WriteLine(customers.ToString());
 
            Console.ReadKey();
        }
    }
}
Posted on Monday, February 1, 2010 8:22 PM LINQ | Back to top

Copyright © Joe Mayo | Powered by: GeeksWithBlogs.net