1
我有一個關於從命名空間xml中檢索節點的問題。只要我在查詢中指定xml的單個元素,我就可以檢索所有匹配的元素,並且可以遍歷他們的子元素。我嘗試通過指定更詳細的查詢來檢索單個唯一元素時,出現問題。如何使用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">
<Streams>
<Samples>
<Position dataItemId="xs4" timestamp="2012-11-29T12:30:19Z" sequence="1718269" name="x_pos_cmd" subType="COMMANDED" units="MILLIMETER">1</Position>
<Position dataItemId="xs5" timestamp="2012-11-29T12:30:19Z" sequence="1718270" name="x_pos_act" subType="ACTUAL" units="MILLIMETER">2</Position>
<Position dataItemId="xs4" timestamp="2012-11-29T12:30:19Z" sequence="1718269" name="y_pos_cmd" subType="COMMANDED" units="MILLIMETER">3</Position>
<Position dataItemId="xs4" timestamp="2012-11-29T12:30:19Z" sequence="1718269" name="y_pos_act" subType="COMMANDED" units="MILLIMETER">4</Position>
<Position dataItemId="xs4" timestamp="2012-11-29T12:30:19Z" sequence="1718269" name="z_pos_cmd" subType="COMMANDED" units="MILLIMETER">5</Position>
</Samples>
<Condition>
<Unavailable dataItemId="xc1" type="POSITION" timestamp="2012-11-27T23:19:40Z" sequence="7" name="x_cond_pos">UNAVAILABLE</Unavailable>
<Unavailable dataItemId="xc2" type="LOAD" timestamp="2012-11-27T23:19:40Z" sequence="8" name="x_cond_load">UNAVAILABLE</Unavailable>
</Condition>
</Streams>
</MTConnectStreams>
考慮下面的代碼:
Dim xIt As XPathNodeIterator
Dim xDoc As XmlDocument = New XmlDocument
xDoc.Load("c:\Download\Test.xml")
Dim xNav As XPathNavigator = xDoc.CreateNavigator
Dim nsMgr = New XmlNamespaceManager(xNav.NameTable)
nsMgr.AddNamespace("ns", "urn:mtconnect.org:MTConnectStreams:1.2")
sQuery = "//ns:Samples"
xIt = xNav.Select(sQuery, nsMgr)
MsgBox(xIt.Count.ToString)
When sQuery = "//ns:Samples" (1 result)
When sQuery = "//ns:Position" (5 results)
When sQuery = "//ns:Samples/Position (0 results why?)
When sQuery = "//ns:Samples/Position[@name='x_pos_act'] (0 results)
When sQuery = "//ns:Position[@name='x_pos_act']" (0 results)
When sQuery = "//ns:Position/[@name='x_pos_act']" (0 results)
等等等等,只要查詢比單個節點名稱我沒有得到任何結果的更多。我無法弄清楚如何指定更詳細的查詢。
謝謝。就是這樣。奇怪的是不得不反覆指定命名空間。看起來像你應該能夠做一些事情,比如在你的導航器或迭代器對象的屬性中設置你想要處理的命名空間,它會假設你是指你的命名空間。無論如何,再次感謝您的幫助。 – Robb 2013-03-14 17:26:06