2013-03-14 69 views
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) 

等等等等,只要查詢比單個節點名稱我沒有得到任何結果的更多。我無法弄清楚如何指定更詳細的查詢。

回答

1

它應該使用//ns:Samples/ns:Position

AFAIK XPath中,你必須指定每個分部命名空間前綴。這也適用於屬性!

所以嘗試:

When sQuery = "//ns:Samples" 
When sQuery = "//ns:Position" 
When sQuery = "//ns:Samples/ns:Position 
When sQuery = "//ns:Samples/ns:Position[@ns:name='x_pos_act'] 
When sQuery = "//ns:Position[@ns:name='x_pos_act']" 
When sQuery = "//ns:Position/[@ns:name='x_pos_act']" 

如果你不想考慮命名空間,你也可以使用@*[local-name()='Samples']語法。這將忽略所有的名稱空間,只檢查節點名稱本身。

+0

謝謝。就是這樣。奇怪的是不得不反覆指定命名空間。看起來像你應該能夠做一些事情,比如在你的導航器或迭代器對象的屬性中設置你想要處理的命名空間,它會假設你是指你的命名空間。無論如何,再次感謝您的幫助。 – Robb 2013-03-14 17:26:06

相關問題