使用xpath从xml文件中检索一个节点

时间:2013-09-27 14:22:21

标签: xml vb.net xpath

我第一次尝试使用xpath和strip xml,

我想要做的就是在调试窗口中显示第一个节点,这是我的代码。

' Create a WebRequest to the remote site
    Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("http://hatrafficinfo.dft.gov.uk/feeds/datex/England/CurrentRoadworks/content.xml")
    Dim response As System.Net.HttpWebResponse = request.GetResponse()

    ' Check if the response is OK (status code 200)
    If response.StatusCode = System.Net.HttpStatusCode.OK Then


        Dim stream As System.IO.Stream = response.GetResponseStream()
        Dim reader As New System.IO.StreamReader(stream)
        Dim contents As String = reader.ReadToEnd()
        Dim document As New System.Xml.XmlDocument()

        document.LoadXml(contents)

        Dim node As System.Xml.XmlNode

        For Each node In document
            Debug.Print(node.SelectNodes("/situation").ToString())
        Next node

    Else

        Throw New Exception("Could not retrieve document from the URL, response code: " & response.StatusCode)

    End If

感谢任何人都能给予的帮助!!!

这是xml doument的开头

 <d2LogicalModel modelBaseVersion="1.0">
  <exchange>
    <supplierIdentification>
       <country>gb</country>
       <nationalIdentifier>NTCC</nationalIdentifier>
    </supplierIdentification>
  </exchange><payloadPublication xsi:type="SituationPublication" lang="en">   <publicationTime>2013-09-27T16:09:02+01:00</publicationTime>

GB

2 个答案:

答案 0 :(得分:1)

使用SelectSingleNode Function尝试此操作。

Dim xrn As XmlNode
Dim xd As New XmlDocument()
xd.LoadXml(xml)
xrn = xd.SelectSingleNode("//")

If Not IsNothing(xrn) Then
    mac = xrn.InnerText
End If

ozoid ..

答案 1 :(得分:1)

首先,您需要在文档上调用select方法,而不是在null节点变量上调用:

'This will not work because node is null (Nothing)
node.SelectNodes("/situation")

'This will work
document.SelectNodes("/situation")

SelectNodes方法返回节点集合。如果您想要的只是第一个,请改为呼叫SelectSingleNodes,如下所示:

node = document.SelectSingleNode("/situation")

然后,根据您的偏好,不是在节点上调用ToString,而是调用InnerXmlInnerTextOuterXml,例如:

node = document.SelectSingleNode("/situation")
If node IsNot Nothing Then
    Debug.Print(node.InnerText)
Else
    Debug.Print("Node does not exist")
End If

但是,在查看您尝试阅读的实际XML之后,将永远找不到该节点。 /situation只会找到节点,如果它是根元素,但在实际的XML文档中,它位于:/d2LogicalModel/payloadPublication/situation。但是,还存在第二个问题。在根元素上定义了一个默认命名空间:xmlns="http://datex2.eu/schema/1_0/1_0"。因此,您需要在select中明确指定命名空间,如下所示:

Dim doc As New XmlDocument()
doc.Load("http://hatrafficinfo.dft.gov.uk/feeds/datex/England/CurrentRoadworks/content.xml")
Dim nsmgr As New XmlNamespaceManager(doc.NameTable)
nsmgr.AddNamespace("x", "http://datex2.eu/schema/1_0/1_0")
Dim node As XmlNode = doc.SelectSingleNode("/x:d2LogicalModel/x:payloadPublication/x:situation", nsmgr)
If node IsNot Nothing Then
    Debug.Print(node.InnerXml)
Else
    Debug.Print("Node does not exist")
End If

请注意,无需创建HttpWebRequest,因为XmlDocument类能够直接从URI加载。