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.
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 :
VB.Net Examples :
ProductCatalog.xml File :
Output:
Below are the books that you would like :
- 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.
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:
Below are the books that you would like :
No comments:
Post a Comment