Peter Sun
Peter Sun

Reputation: 1835

VB.net XPath Not getting NodeList

I have an XML doc:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<Root xmlns="u" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="/xml/abc.xsd">
    <DOCID>123456789</DOCID>
    ...
    <Body>
        <Problems>
            <Problem>Data1
            </Problem>
            <Problem>Data2
            </Problem>
            <Problem>Data3
            </Problem>
        </Problems>
    </Body>
</Root>

I am trying to get the list of problems in the XML document above. I am using .SelectNodes to get the nodes. See the following code:

Private Sub GetProblems(ByVal xml As XmlDocument)
            Dim nodeList As XmlNodeList = xml.SelectNodes("/Root/Body/Problems/Problem")
For Each node As XmlNode In nodeList
  ...
Next
End Sub

The nodeListvariable has a count of 0. I used a free online XPath Tester and used the path above and it worked, but it is not working in VB.NET.

Upvotes: 1

Views: 513

Answers (1)

SSS
SSS

Reputation: 5403

  1. Your XML uses a namespace, so you need a XmlNamespaceManager
  2. Your XPATH needs to include the namespace ("u:")
  3. The text contents are a node by themselves, so you want to add /text() to your XPATH

    Dim xdc As New XmlDocument
    xdc.Load("Myfilename.xml")
    Dim strXPATH As String = "/u:Root/u:Body/u:Problems/u:Problem/text()"
    Dim nsmgr As New XmlNamespaceManager(xdc.NameTable)
    nsmgr.AddNamespace("u", xdc.DocumentElement.NamespaceURI)
    Dim xnl As XmlNodeList = xdc.DocumentElement.SelectNodes(strXPATH, nsmgr)
    For Each xnd As XmlNode In xnl
      MsgBox(strXPATH & "=" & xnd.Value)
    Next
    

Upvotes: 1

Related Questions