2012-08-13 74 views
1

我有以下簡單的XML文檔:讀通過XPath的XML文檔中的屬性不起作用

<?xml version="1.0" encoding="utf-8"?> 
<Research researchID="RT_a" language="eng" xmlns="http://www.rixml.org/2010/1/RIXML" createDateTime="2012-06-30T01:13:38Z"> 
    <Product productID="RT_a"> 
       <SecurityID idType="ISIN" idValue="US0605051046" /> 
    </Product> 
</Research> 

我想讀屬性「idValue」使用給定的XPath字符串。這並不工作,除非我刪除了這部分:

xmlns="http://www.rixml.org/2010/1/RIXML" 

我的代碼如下:

Dim doc As XPathDocument = New XPathDocument("c:\test\test.xml") 

    Dim strXPath As String = "/Research[1]/Product[1]/SecurityID[1]" 
    Dim nav As XPathNavigator = doc.CreateNavigator() 
    Dim mgr As New XmlNamespaceManager(nav.NameTable) 

    mgr.AddNamespace("", "http://www.rixml.org/2010/1/RIXML") 

    Dim XPathNode As XPathNavigator = nav.SelectSingleNode(strXPath, mgr) 
    If XPathNode IsNot Nothing Then 
     Console.WriteLine(XPathNode.GetAttribute("idValue", String.Empty)) 
    Else 
     Console.WriteLine("Nothing found") 
    End If 

有關添加名稱空間行對結果沒有任何影響 - 只是做了一些測試這一點。我需要做什麼/我做錯了什麼?

回答

1

嘗試以下操作:

Dim strXPath As String = "/x:Research[1]/x:Product[1]/x:SecurityID[1]/@idValue" 
Dim nav As XPathNavigator = doc.CreateNavigator() 
Dim mgr As New XmlNamespaceManager(nav.NameTable) 

mgr.AddNamespace("x", "http://www.rixml.org/2010/1/RIXML") 
nav.Evaluate("string(" + strXPath + ")", mgr) 

應該回到你的ID值,或則一個空字符串,如果沒有找到該屬性。

我認爲問題可能是here列出的問題,您必須顯式引用命名空間(即使它是默認的),所以通過使用「x:」您可以修復它。

+0

非常感謝 - 它效果很好! – serializer 2012-08-14 16:22:00