Monday, 15 July 2013

.Net Tips : Get all attributes value from XML file or document using LINQ with C#.Net and VB.Net example

We can get specific attributes values from XML file or document or object using LINQ. We are using "Elements" and "Attributes" methods of XML document object to get attributes values.

Here is example for this.
In this example we take one "BooksList.xml" file. This file contains books related details and each book has ISBN number which appears as attribute in "<book>" node. We retrieve this attribute using LINQ and display on screen.

C#. Net Example :

    XDocument objXLDoc = XDocument.Load(Server.MapPath( "BooksList.xml"));
    var objQuery = objXLDoc.Element("books").Elements("book").Attributes("ISBN");
    Response.Write("<b>Attributes and its value list :</b><br/><br/>");
    foreach (XAttribute objResult in objQuery)
        Response.Write(objResult.Name + " = " + objResult.Value);

VB.Net Examples :

        Dim objXLDoc As XDocument = XDocument.Load(Server.MapPath("BooksList.xml"))
        Dim objQuery = objXLDoc.Element("books").Elements("book").Attributes("ISBN")
        Response.Write("<b>Attributes and its value list :</b><br/><br/>")
        For Each objResult As XAttribute In objQuery
            Response.Write(objResult.Name.ToString() & " = " & objResult.Value.ToString)

XML File ("BooksList.xml") :

<?xml version="1.0" encoding="utf-16"?>
  <book ISBN="asp1">
  <book ISBN="c#2">

Output :

Below are the books that you would like :


  1. nice tip jayesh...what next.

  2. You are using for-each-loop, how is it using LINQ?

  3. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. Dot Net Training in chennai | dot net training institute in velachery

  4. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.. dot net training in chennai | best dot net training in chennai