我第一次尝试使用 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文件的开始
<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>
国标
最佳答案
首先,您需要在文档上调用 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
,而是调用 InnerXml
、InnerText
或 OuterXml
,取决于您的喜好,例如:
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 加载。
关于xml - 使用 xpath 从 xml 文件中检索一个节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19053154/