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?