Thursday, 5 July 2012

.Net Tips , C# tip : Read and Processing XML file with an Xdocument with C# Examples and VB.Net Examples

XDocument is Introduce in System.Xml.Linq namespace.
XDocument is more friendlier and easy to use than XMLDocument.
Earlier we are using XMLDocument for read and processing XML File.
Syntax of retrieving element from XML document is different than XMLDocument.
Every .Net Beginners needs to know this. 

Here is example for this.
In this example We load Books.xml file and read data from this file using LINQ to XML and display in grid as well as display count of books.

XML File : (Books.xml)
<?xml version="1.0" encoding="utf-8" ?>
    <Title>SQL Server</Title>

ASPX Code :
<form id="form1" runat="server">
        <asp:GridView ID="gvBooks" runat="server">

C# Example :
        XDocument objBooksXML = XDocument.Load(Server.MapPath("books.xml"));
        var objBooks = from book in
                       select new { 
                                    Title = book.Element("Title").Value, 
                                    Pages = book.Element("Pages").Value 

        Response.Write(String.Format("Total {0} books.", objBooks.Count()));
        gvBooks.DataSource = objBooks;
        gvBooks.DataBind(); Example :
        Dim objBooksXML As XDocument = XDocument.Load(Server.MapPath("books.xml"))
        Dim objBooks = From book In objBooksXML...<Book>
                       Select New With {.Title = book.<Title>.Value, .Pages = book.<Pages>.Value}
        Response.Write(String.Format("Total {0} books.", objBooks.Count()))
        gvBooks.DataSource = objBooks

Output : 

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that. 


  1. useful. i guess xdocument is faster than xmldocument because of linq used there. m i right?

    Also, in any LINQ query what does "new" keyword stands for? (above in C# example). why do we use that?

    1. Hi,
      xDocument is latest class and it's provide linq support so that easy to use.

      "New" keyword is use for custom column projection. We can give custom column name.