2011-04-26 83 views
1

我想傳入一個xpath查詢並返回我找到的值。 我正在尋找特定的屬性值。如何使用XPath獲取c#中屬性的值?

_query = "//@RequestType"; 

我可以返回節點,但我不知道如何從中獲取字符串值。 我想查詢下面的xml的type屬性,並獲得「xpath」。

這也將是很好,如果我可以只是替換我的查詢,也從好的價值「是」回來。

<?xml version="1.0" ?> 
<test type="xpath"> 
    <nice>yes</nice> 
</test> 

C#

public string Locate(string message) 
     { 
    using (var stream = new MemoryStream(Encoding.GetBytes(message))) 
    { 
     var doc = new XPathDocument(stream); 
     var nav = doc.CreateNavigator(); 
     var result = nav.Select(_query); 
     if (result != null) 
     { 
      return result 
     } 
    } 
    } 

回答

1

我的XPath是弱在最好的,但嘗試以下方法:

var doc = new XPathDocument(stream); 
var nav = doc.CreateNavigator();  
foreach (XPathNavigator test in nav.Select("test")) 
{ 
    string type = test.SelectSingleNode("@type").Value; 
    string nice = test.SelectSingleNode("nice").Value; 
    Console.WriteLine(string.Format("Type: {0} - Nice: {1}", type, nice)); 
} 
0

如果你所得到的「測試」節點回到您的查詢,它包含一個名爲「好」,那麼你需要選擇從「好」子節點的子節點父節點「測試」節點並返回它的InnerText以便從中獲得字符串「是」。

我不知道該回答你的問題,因爲我不認爲我完全跟着你在問什麼,但希望這有助於

0

XPathNavigator有一個Value屬性,它將以字符串的形式返回當前節點的值。如果您已經知道數據的類型,您還可以使用ValueAsBoolean,ValueAsDateTime等。