我来自vb6背景。新的.net和xml新手。我试图从xml文件中检索节点。我找到了几个使用的方法(xmltextreader / serialization,xmldocument,xpath)我正在使用xpath只是因为我先得到了一些结果:)我的问题我确定是命名空间相关但我找到的所有例子都比我有的xml。这是我需要访问的xml的一部分以及我的代码片段。
<?xml version="1.0" encoding="utf-8"?>
<MTConnectStreams xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:mtconnect.org:MTConnectStreams:1.2 http://mtconnect.org/schemas/MTConnectStreams_1.2.xsd" xmlns="urn:mtconnect.org:MTConnectStreams:1.2">
<Header creationTime="2012-11-29T12:30:19Z" instanceId="2" nextSequence="1918272" sender="Tarus MTConnect Instance" bufferSize="5000" firstSequence="1913272" lastSequence="1918271" version="1.2" />
<Streams>
<DeviceStream name="Vertical Bridge" uuid="TPIVB1">
<ComponentStream component="Device" name="Vert" componentId="TPIVert">
<Events>
<Availability dataItemId="avail" timestamp="2012-11-27T23:19:40Z" sequence="44">AVAILABLE</Availability>
</Events>
</ComponentStream>
<ComponentStream component="Linear" name="X" componentId="X">
<Samples>
<AxisFeedrate dataItemId="xs1" timestamp="2012-11-29T12:29:54Z" sequence="1717806" name="x_feed_cmd" subType="COMMANDED" units="MILLIMETER/SECOND">0</AxisFeedrate>
尝试检索AxisFeedrate我有这个:
Dim xDoc As XPathDocument = New XPathDocument(sUrl)
Dim xNav As XPathNavigator = xDoc.CreateNavigator
Dim xIt As XPathNodeIterator = xNav.Select("//AxisFeedrate")
Dim i As Integer
For i = 1 To xIt.Count
xIt.MoveNext()
msgbox (xIt.Current.Value)
如果我将根节点更改为“MTConnectStreams”,一切正常。在线命名空间示例后,我对我的代码进行了以下更改。但是在恢复原始根节点时,我仍然得到零结果。
Dim nsMgr = New XmlNamespaceManager(xNav.NameTable)
nsMgr.AddNamespace("ns", "http://www.w3.org/2001/XMLSchema-instance")
Dim xIt As XPathNodeIterator = xNav.Select("//ns:AxisFeedrate", nsMgr)
有人能帮助我克服这个障碍吗?
答案 0 :(得分:1)
您的根节点声明默认命名空间是“urn:mtconnect.org:MTConnectStreams:1.2”,因此您需要使用它:
Dim nsMgr = New XmlNamespaceManager(xNav.NameTable)
nsMgr.AddNamespace("mt", "urn:mtconnect.org:MTConnectStreams:1.2")
Dim xIt As XPathNodeIterator = xNav.Select("//mt:AxisFeedrate", nsMgr)