LINQ to XML : Creating XML from another XML

Based on my previous post if I have to filter the list of customers only in the country “US” and create another XML which may look like,


<?xml version="1.0" encoding="utf-8"?>



    <title>Marketing Manager</title>

    <name>Howard Snyder</name>



    <title>Sales Representative</title>

    <name>Yoshi Latimer</name>



    <title>Marketing Manager</title>

    <name>John Steel</name>





To get this if I have to use the System.Xml namespace then code will become something like,


//Conventional XML way to generate another XML out of this XML

XmlDocument customers = new XmlDocument();


XmlDocument usaCustomers = new XmlDocument();

XmlElement usaRoot = usaCustomers.CreateElement("usaCustomers");


foreach (XmlNode n in customers.SelectNodes(



    XmlElement usaCustomer = usaCustomers.CreateElement("usaCustomer");

    XmlElement usaTitle = usaCustomers.CreateElement("title");

    usaTitle.InnerText = n.Attributes["contactTitle"].Value;


    XmlElement usaContact = usaCustomers.CreateElement("name");

    usaContact.InnerText = n.Attributes["contactName"].Value;





This approach works perfectly fine but for this you also need to learn XPath and XQuery on top of conventional System.Xml.


To achieve this in simple “what you think what you write” scenario you can go for LINQ to XML.


//LINQ to XML way

XElement root = new XElement("usaCustomers",

                from c in XElement.Load(@"C:\XMLData.xml").Descendants("customer")

                where (string)c.Attribute("country") == "USA"

                select new XElement("usaCustomer",

                    new XElement("title", (string)c.Attribute("contactTitle")),

                    new XElement("name", (string)c.Attribute("contactName"))));


Its simple its magic. Thanks to Mike Taulty for my learning.