Thursday, 26 September 2013

C# Tips : Get Full Path of XML Node using LINQ with C#.Net and VB.Net example

We can get or retrieve full path of the given XML Node or Element. Means from root element to the given XML Node. We can achieve this  LINQ's extensions methods. We are using 'Descendants', 'AncestorsAndSelf' and 'Reverse' methods.

  • Descendants : Returns filtered collections of the given elements from document or element. For more details Click Here.
  • AncestorsAndSelf : Returns collection of elements that contain this element. For more details Click Here.

Here is C#.Net example and VB.Net example.

In this example we take one "ProductCatalog.xml" file. In this XML we have one inner XML node called "inStock". Now we retrieve full path of the "inStock" node from root to "inStock" node. You can see that into output image.

C#. Net Example :
        XDocument objDoc = XDocument.Load(Server.MapPath("ProductCatalog.xml"));
        XElement objElement = objDoc.Descendants("inStock").First();

        var objNodes = objElement.AncestorsAndSelf().Reverse();
        foreach (var n in objNodes)
            Response.Write(n.Name + (n == objElement ? "" : " -> "));

VB.Net Examples :
        Dim objDoc As XDocument = XDocument.Load(Server.MapPath("ProductCatalog.xml"))
        Dim objElement As XElement = objDoc.Descendants("inStock").First()

        Dim objNodes = objElement.AncestorsAndSelf().Reverse()
        For Each n As XElement In objNodes
            Response.Write(Convert.ToString(n.Name) & (If(n.Equals(objElement), "", " -> ")))
        Next

ProductCatalog.xml File :
<?xml version="1.0"?>
<productCatalog>
  <catalogName>New Catalog</catalogName>
  <expiryDate>2013-08-28</expiryDate>
  <products>
    <product>
      <productName>Product 1</productName>
      <productPrice>42.99</productPrice>
      <inStock>false</inStock>
    </product>
    <product>
      <productName>Product 2</productName>
      <productPrice>202.99</productPrice>
      <inStock>false</inStock>
    </product>
  </products>
</productCatalog>

Output: 
Get Full Path of XML Node using LINQ


Below are the books that you would like :

No comments:

Post a Comment