Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to Start with XML and LINQ: A Beginner Guide.

0.00/5 (No votes)
12 Jun 2012 1  
How we can utilize power of LINQ with XML data.

Introduction

In this article we are going to show you some good stuff of LINQ with XML data.

Quick View   

I am assuming that you are aware of XML. So i am not going to cover basic XML Element, Attributes. And hope you are aware about where and why you need to use XML.

Lets see our sample XML Data:

<Products>
  <Product id="1">
    <Name>Desktop Computer</Name>
    <Stock>12</Stock>
    <ModelNo>DC001</ModelNo>
    <Price>20000</Price>    
  </Product>
  <Product id="2">
    <Name>Compuetr Mouse</Name>
    <Stock>100</Stock>
    <ModelNo>CM001</ModelNo>
    <Price>800</Price>    
  </Product>
  <Product id="3">
    <Name>Printer</Name>
    <Stock>10</Stock>
    <ModelNo>PR001</ModelNo>
    <Price>5900</Price>
  </Product>
</Products>

Now we are going to look into how LINQ will be helpful for

1) Creating New XML Document

2) Query on XML Document

3) Adding/Appending New Nodes

4) Deleting Particular Node

Jump on LINQ with simple example

To use XDocument, XElement, or XAttribute we need to include System.Xml.Linq namespace in our code. We will see all the point one by one with example. Let's start with XDocument.

Example1: Load un-parsed XML string into XDocument

string myXML = "<Products><Product>Laptop</Product><Product>Printer</Product><Product>Mouse</Product></Products>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);

Output:(xdoc content)

<Products>
  <Product>Laptop</Product>
  <Product>Printer</Product>
  <Product>Mouse</Product>
</Products> 

Above scenario is when we have well-formed XML data. What if we do not have idea about XML data. XmlException will occur if myXML contain some incorrect format of xml data. In all given examples, we have many options with different constructor. i am going to cover only some of the constructor. you can refer MSDN for getting information about all the available constructor.

Example2 : Adding Node in existing XDocument

string myXML = "<Products><Product>Laptop</Product><Product>Printer</Product><Product>Mouse</Product></Products>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);
// Add one more Product in xdoc 
xdoc.Element("Products").Add(new XElement("Product", "Mobile"));

Output:(xdoc content)

<Products>
  <Product>Laptop</Product>
  <Product>Printer</Product>
  <Product>Mouse</Product>
  <Product>Mobile</Product>
</Products> 

As you can see we have added one new Product in our xml list. As we are parsing xml data from string value. we can also load xml data from file. XDocument.Load is the method we can use to load xml data from file.

Example3: Adding Node at first position in existing XDocument

string myXML = "<Products><Product>Laptop</Product><Product>Printer</Product><Product>Mouse</Product></Products>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);
// Add one more Product at first position in xdoc             
xdoc.Element("Products").AddFirst(new XElement("Product", "Mobile"));
 

Output:(xdoc content)

<Products>
  <Product>Mobile</Product>
  <Product>Laptop</Product>
  <Product>Printer</Product>
  <Product>Mouse</Product>
</Products> 

Now let's take a real life example of getting product name with character length equals to 6. with old methodology we normally iterate through all the elements and check if length is 6 or not. but now with the help of LINQ we can do it with very simple query.

Example4: Get Elements with product name equals to 6 digits

string myXML = "<Products><Product>Laptop</Product><Product>Printer</Product><Product>Mouse</Product></Products>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);
// Add one more Product at first position in xdoc             
xdoc.Element("Products").AddFirst(new XElement("Product", "Mobile"));
var result = xdoc.Element("Products").Descendants().Where(s => s.Value.Length == 6);  

Output:(result content)

<Product>Mobile</Product>
<Product>Laptop</Product>

There are so many other methods available that can be helpful to add element in hierarchy, remove element. We can also save the xml document with xdoc.Save(filename) method. hope this information will be enough to start with XDocument. Now let's look at two major part of XML document i.e. XElement, XAttribute.

Play with Dynamic XML

This topic will cover about XElement, XAttribute and XNode. Main part of the xml is Elements and attributs.

Example5: Creating Nesting of XElement chain

XElement xElement = new XElement("Products", 
                new XElement("Product", "computer"),
                new XElement("Product", "laptop"),
                new XElement("Product", "mouse"),
                new XElement("Product", "keyboard")
                );

Output:(xElement content)

<Products>
  <Product>computer</Product>
  <Product>laptop</Product>
  <Product>mouse</Product>
  <Product>keyboard</Product>
</Products> 

Example6: Creating XML with XElement and XAttribute

XElement xElement = new XElement("Products",
                new XElement("Product", "computer", new XAttribute("ID", "1")),
                new XElement("Product", "laptop", new XAttribute("ID", "2")),
                new XElement("Product", "mouse", new XAttribute("ID", "3")),
                new XElement("Product", "keyboard", new XAttribute("ID", "4"))
                );

Output:(xElement content)

<Products>
  <Product ID="1">computer</Product>
  <Product ID="2">laptop</Product>
  <Product ID="3">mouse</Product>
  <Product ID="4">keyboard</Product>
</Products>  

Example7: Remove element from XML data

XElement xElement = new XElement("Products",
                new XElement("Product", "computer", new XAttribute("ID", "1")),
                new XElement("Product", "laptop", new XAttribute("ID", "2")),
                new XElement("Product", "mouse", new XAttribute("ID", "3")),
                new XElement("Product", "keyboard", new XAttribute("ID", "4"))
                );

xElement.Descendants().Where(s => s.Attribute("ID").Value == "2").Remove(); 

Output:(xElement content)

<Products>
  <Product ID="1">computer</Product>
  <Product ID="3">mouse</Product>
  <Product ID="4">keyboard</Product>
</Products>  

You will not be expert after reading this article but at least you will find this helpful to start working with LINQ and XML. once you complete all the understanding of the LINQ and XML, you can resolve complicated problems with this feature.

I found this very easy to use and to maintain. hope you will also like this article. Although i have not covered all the property and methods of XElement, XAttribute, XNode , etc... but this information is enough to start working with XML. 

Next Step (Reference book and link)

C# 4.0 Nutshell (Read chapter 10, Must read)  

LINQ to XML MSDN 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here