LINQ to XML : Creating XML from another XML

LINQ to XML : Creating XML from another XML

  • Comments 5

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"?>

<usaCustomers>

  <usaCustomer>

    <title>Marketing Manager</title>

    <name>Howard Snyder</name>

  </usaCustomer>

  <usaCustomer>

    <title>Sales Representative</title>

    <name>Yoshi Latimer</name>

  </usaCustomer>

  <usaCustomer>

    <title>Marketing Manager</title>

    <name>John Steel</name>

  </usaCustomer>

….

 

 

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();

customers.Load(@"C:\XMLData.xml");

 

XmlDocument usaCustomers = new XmlDocument();

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

usaCustomers.AppendChild(usaRoot);

 

foreach (XmlNode n in customers.SelectNodes(

    "/customers/customer[@country='USA']"))

{

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

 

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

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

    usaCustomer.AppendChild(usaTitle);

 

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

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

    usaCustomer.AppendChild(usaContact);

 

    usaRoot.AppendChild(usaCustomer);

}

 

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.

 

Namoskar!!!

Leave a Comment
  • Please add 6 and 5 and type the answer here:
  • Post
Page 1 of 1 (5 items)