Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / C# 4.0

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

Rate me:
Please Sign up or sign in to vote.
4.65/5 (8 votes)
11 Jun 2012CPOL3 min read 65.5K   923   43   8
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:

XML
<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

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

Output:(xdoc content)

XML
<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

C#
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)

XML
<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

C#
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)

XML
<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

C#
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)

XML
<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

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

Output:(xElement content)

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

Example6: Creating XML with XElement and XAttribute

C#
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)

XML
<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

C#
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)

XML
<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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Franc Morales17-Apr-15 23:27
Franc Morales17-Apr-15 23:27 
QuestionFix for a problem that happened Pin
Alex Kinney23-Oct-13 11:51
Alex Kinney23-Oct-13 11:51 
GeneralMy vote of 5 Pin
asafgb28-Jul-13 22:25
asafgb28-Jul-13 22:25 
GeneralRe: My vote of 5 Pin
AmitGajjar29-Jul-13 0:42
professionalAmitGajjar29-Jul-13 0:42 
Question[My vote of 2] Something missing Pin
Richard MacCutchan18-Jun-12 7:00
mveRichard MacCutchan18-Jun-12 7:00 
AnswerRe: [My vote of 2] Something missing Pin
AmitGajjar18-Jun-12 18:10
professionalAmitGajjar18-Jun-12 18:10 
GeneralMy vote of 5 Pin
jbachelor13-Jun-12 19:07
jbachelor13-Jun-12 19:07 
GeneralRe: My vote of 5 Pin
AmitGajjar13-Jun-12 20:16
professionalAmitGajjar13-Jun-12 20:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.