3

我第一次尝试使用 xpath 和剥离 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>

国标

4

2 回答 2

1

用 SelectSingleNode 函数试试这个。

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

氧化锌..

于 2013-09-27T14:28:26.253 回答
1

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

'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". 因此,您需要在您的选择中明确指定命名空间,如下所示:

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 加载。

于 2013-09-27T14:45:18.820 回答