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 :
VB.Net Examples :
XML File ("BooksList.xml") :
Output :
Below are the books that you would like :
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); Response.Write("<br/>"); }
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) Response.Write("<br/>") Next
XML File ("BooksList.xml") :
<?xml version="1.0" encoding="utf-16"?> <books> <book ISBN="asp1"> <Title>ASP.NET</Title> <ReleaseDate>11/11/2010</ReleaseDate> <Pages>200</Pages> </book> <book ISBN="c#2"> <Title>C#.NET</Title> <ReleaseDate>10/11/2010</ReleaseDate> <Pages>500</Pages> </book> </books>
Output :
Below are the books that you would like :
nice tip jayesh...what next.
ReplyDeleteYou are using for-each-loop, how is it using LINQ?
ReplyDeleteIt is really a great work and the way in which u r sharing the knowledge is excellent.
ReplyDeleteThanks 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