XPath查询在XPath测试程序中工作,但在VB.NET中没有

时间:2014-07-18 21:25:20

标签: .net xml vb.net xpath .net-4.0

为什么这个XPath会在XPath Tester中返回结果,但在我的代码中却没有?我认为我忽视了一些简单的事情。

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

配置:

<?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 个答案:

答案 0 :(得分:2)

目前尚不清楚你是如何在XPath测试中进行测试的(或者你测试的XPath表达式究竟是什么),但我认为你的代码是公平的,因为它试图让节点具有路径配置 - &gt;状态 - &gt;状态 - &gt; ElementOne显然不存在:

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

您可以通过以下方式修复xpath变量值:

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

或这种方式(开头的单个句点(.)是强制性的):

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

或者如果可能,只需在一行中获取正确的节点:

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