VB.net XPath没有得到NodeList

时间:2018-01-11 23:52:55

标签: xml vb.net xpath

我有一个XML文档:

<?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>

我正在尝试获取上面XML文档中的问题列表。我正在使用.SelectNodes来获取节点。请参阅以下代码:

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

nodeList变量的计数为0.我使用了免费的在线XPath测试程序并使用了上面的路径并且它有效,但它在VB.NET中不起作用。

1 个答案:

答案 0 :(得分:0)

  1. 您的XML使用命名空间,因此您需要XmlNamespaceManager
  2. 您的XPATH需要包含命名空间(“u:”)
  3. 文本内容本身就是一个节点,因此您要将/text()添加到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