0

Why does this XPath return a result in XPath Tester, but not in my code? I think that I'm overlooking something simple.

Sub Main()
    Dim doc As New XmlDocument()
    doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile)

    Dim xmlNode As XmlElement = TryCast(doc.SelectSingleNode("/configuration/Status"), XmlElement)
    Dim xpath = "/Status/ElementOne[@ID='1234']"

    Console.WriteLine(xmlNode.OuterXml)

    Console.WriteLine()

    Console.WriteLine(xpath)

    Dim eFileEvent = xmlNode.SelectSingleNode(xpath)

    Console.WriteLine()
    Console.WriteLine("Results")

    If (eFileEvent Is Nothing) Then
        Return
    End If

    Console.WriteLine(eFileEvent.OuterXml)
End Sub

Config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
  <configSections>
    <section name="Status" type="System.Configuration.IgnoreSectionHandler,     System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
         allowLocation="false" />
  </configSections>
  <Status xmlns="">
    <ElementOne ID="1234"></ElementOne>
  </Status>
</configuration>

1 Answer 1

2

It isn't clear how you did the test in XPath tester (or what exactly the XPath expression you tested), but I think your code is fair to fail because it is trying to get node having path configuration -> Status -> Status -> ElementOne which clearly doesn't exist :

Dim xmlNode As XmlElement = TryCast(doc.SelectSingleNode("/configuration/Status"), XmlElement)
Dim xpath = "/Status/ElementOne[@ID='1234']"

You can either fix the xpath variable value this way :

Dim xpath = "ElementOne[@ID='1234']"

or this way (single period (.) at the beginning is mandatory) :

Dim xpath = "./ElementOne[@ID='1234']"

or if possible, just get the right node in one line :

Dim xmlNode As XmlElement = doc.SelectSingleNode("/configuration/Status/ElementOne[@ID='1234']")
Sign up to request clarification or add additional context in comments.

1 Comment

I'm mocking some data through the web.config temporarily. I didn't realize that when I ran the second xpath query, starting the query with '/' took me back to the root of the xml. As you stated, I had to drop the forward slash, or use a period. Many thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.