Monday, 26 August 2013

C# Tips : Get Parent Element from Child Element In XML using LINQ with C#.Net and VB.Net example

You can get Parent element from child element using LINQ method. Some times there are situations when you traverse XML file and you reach at child node and you want to get details of Parent node at that time you can use "Parent" method which will give you parent node as XElement object.

Here is example for this.
In this example we took one "BooksList.xml" file. Now we traverse to child node "Title" and after that, we get its parent node using "Parent" property.
C#. Net Example :

        XDocument objXDOC = XDocument.Load(Server.MapPath("BooksList.xml"));

        XElement[] objElement = objXDOC.Elements("books").Elements("book").Elements("Title").ToArray();
        Response.Write("<b>Name of parent element is : </b>"  + objElement[0].Parent.Name);

VB.Net Examples :

        Dim objXDOC As XDocument = XDocument.Load(Server.MapPath("BooksList.xml"))

        Dim objElement() As XElement = objXDOC.Elements("books").Elements("book").Elements("Title").ToArray()

        Response.Write("<b>Name of parent element is : </b>" & objElement(0).Parent.Name.ToString())


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

Output : 

Below are the books that you would like :

No comments:

Post a Comment