Wednesday, 11 September 2013

C# Tips : Get XML Element of particular position from XML Document using LINQ positional predicate with C#.Net and VB.Net example

You can directly get element of particular position or query that element using LINQ's 'Descendants' and 'ElementAt' method.

  • 'Descendants' is a method of XDocument class which accept name of element as string.
  • 'ElementAt' is a method of 'XElement' class which accept integer value of index.

Means you can query the 2nd book element in the XML document or file. You can also call that as positional predicate.

Here is example for this.
In this example we took one XML file 'BooksList.xml'. Now we use 'Descendants' method of 'XDocument' and pass 'book' element and after that, we use 'ElementAt' method and pass '1' so that we can get 2nd element of 'book' from that XML file.

C#. Net Example :
XDocument objDoc = XDocument.Load(Server.MapPath("BooksList.xml"));
XElement objElement = objDoc.Descendants("book").ElementAt(1);

Response.Write("<b>Title Element Value : </b>" + objElement.Element("Title").Value);
Response.Write("<b>ReleaseDate Element Value : </b>" + objElement.Element("ReleaseDate").Value);
Response.Write("<b>Pages Element Value : </b>" + objElement.Element("Pages").Value);

VB.Net Examples :
Dim objDoc As XDocument = XDocument.Load(Server.MapPath("BooksList.xml"))
Dim objElement As XElement = objDoc.Descendants("book").ElementAt(1)

Response.Write("<b>Title Element Value : </b>" + objElement.Element("Title").Value)
Response.Write("<b>ReleaseDate Element Value : </b>" + objElement.Element("ReleaseDate").Value)
Response.Write("<b>Pages Element Value : </b>" + objElement.Element("Pages").Value)

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

Output :
LINQ positional predicate

Below are the books that you would like :

No comments:

Post a Comment