Search code examples
c#xmlvb.netxpathxpathnavigator

Get all possible XPath expressions with XPathNavigator class?


I already have an algorithm to retrieve the XPath expressions of an Xml:

However, it is imperfect, unsecure, and it needs a lot of additional decoration to format the obtained expressions. ( for an example of desired formatting I mean this: Get avaliable XPaths and its element names using HtmlAgilityPack )

Then, I recently discovered the XPathNavigator class, and to improve in any way the reliability of my current code, I would like to know if with the XPathNavigator class I could retrieve all the XPath exprressions of the Xml document, because that way my algorithm could be based in the efficiency of the .Net framework logic and their rules instead of the imperfect logic of a single programmer.

I search for a solution in C# or Vb.Net.

This is what I tried:

    Dim xDoc As XDocument =
        <?xml version="1.0"?>
        <Document>
            <Tests>
                <Test>
                    <Name>A</Name>
                    <Value>0.01</Value>
                    <Result>Pass</Result>
                </Test>
                <Test>
                    <Name>A</Name>
                    <Value>0.02</Value>
                    <Result>Pass</Result>
                </Test>
                <Test>
                    <Name>B</Name>
                    <Value>1.01</Value>
                    <Result>Fail</Result>
                </Test>
            </Tests>
        </Document>

    Dim ms As New MemoryStream
    xDoc.Save(ms, SaveOptions.None)
    ms.Seek(0, SeekOrigin.Begin)

    Dim xpathDoc As New XPathDocument(ms)
    Dim xpathNavigator As XPathNavigator = xpathDoc.CreateNavigator

    Dim nodes As XPathNodeIterator = xpathNavigator.Select(".//*")

    For Each item As XPathNavigator In nodes
        Console.WriteLine(item.Name)
    Next

With that code I only managed to get this (undesired)kind of output:

Document
Tests
Test
Name
Value
Result
Test
Name
Value
Result
Test
Name
Value
Result
Test
Name
Value
Result

Is possibly to extract all the XPath expressions using the XPathNavigator class?.


Solution

  • No, that's not possible. There are many, many ways to select a particular node with XPath. You might settle on some notion of the "canonical" XPath for any given node, but even that sounds hard to specify, and XPathNavigator has no such notion built in to help you.