2013-05-27 70 views
1

我試圖編寫一個XPath表達式來從其「質量」中的值中選擇一個節點的名稱,然後在「qualityNames」中選擇其節點中的值名稱先前已被捕獲。如何編寫XPath表達式來從其值中選擇節點名稱

E.g.在「品質」 - 有值「4」,取的名字「rarity3」,然後在「qualityNames」我得到了節點名爲「rarity3」,並採取值「amazingrarity」

<result> 
    <status>1</status> 
    <qualities> 
    <Normal>0</Normal> 
    <rarity1>1</rarity1> 
    <rarity2>2</rarity2> 
    <vintage>3</vintage> 
    <rarity3>4</rarity3> 
    <rarity4>5</rarity4> 
    </qualities> 
    <qualityNames> 
    <Normal>Normal</Normal> 
    <rarity1>Genuine</rarity1> 
    <rarity2>rarity2</rarity2> 
    <vintage>Vintage</vintage> 
    <rarity3>amazingrarity</rarity3> 
    <rarity4>Unusual</rarity4> 
    </qualityNames> 
</result> 

我在C#這樣做(這是一個MVC應用程序),我寧願使用XPath,因爲我正在爲XML編制索引,而且我還沒有找到查詢內存技術的最快方法(此XML文件大小約爲3MB,而我正在使用IndexingXPathNavigator)。

回答

4

使用local-name()和text()函數+謂詞。對於值「4」將

//qualityNames/*[local-name()=local-name(//qualities/*[text() = '4'])] 

測試與http://www.xpathtester.com

+0

+1 xpathtester.com! – Sphinxxx

+0

感謝編輯,@Sphinxxx - 沒有注意到與星號的問題 – morincer

0

我認爲這是你問

 var rarity3ValueInQualities = xml.SelectSingleNode("/result/qualities/rarity3").InnerText; 
     var rarity3ValueInqualityNames = xml.SelectSingleNode("/result/qualityNames/rarity3").InnerText; 
1

聽起來像是你想創建密鑰的字典/值對(假設節點名稱僅用於查找匹配項並且對您的代碼不重要)。

如果是這樣,你可以使用以下命令:

var doc = XElement.Parse(@"<result> 
<status>1</status> 
<qualities> 
    <Normal>0</Normal> 
    <rarity1>1</rarity1> 
    <rarity2>2</rarity2> 
    <vintage>3</vintage> 
    <rarity3>4</rarity3> 
    <rarity4>5</rarity4> 
</qualities> 
<qualityNames> 
    <Normal>Normal</Normal> 
    <rarity1>Genuine</rarity1> 
    <rarity2>rarity2</rarity2> 
    <vintage>Vintage</vintage> 
    <rarity3>amazingrarity</rarity3> 
    <rarity4>Unusual</rarity4> 
</qualityNames> 
</result>"); 

var query = from quality in doc.XPathSelectElements("qualities/*") 
      join qualityName in doc.XPathSelectElements("qualityNames/*") 
      on quality.Name equals qualityName.Name 
      select new { Key = quality.Value, Value = qualityName.Value }; 
var qualities = query.ToDictionary(a => a.Key, a => a.Value); 
var quality3 = qualities["3"]; 
// quality3 == "Vintage" 
var quality4 = qualities["4"]; 
// quality4 == "amazingrarity" 

編輯:例如如何緩存本字典

// add reference to System.Web dll 
public Dictionary<string, string> GetQualities() 
{ 
    // assuming this code is in a controller 
    var qualities = this.HttpContext.Cache["qualities"] as Dictionary<string, string>; 
    if (qualities == null) 
    { 
     // LoadQualitiesFromXml() is the code above 
     qualities = LoadQualitiesFromXml(); 
     this.HttpContext.Cache["qualities"] = qualities; 
    } 
    return qualities; 
} 
+0

是的..問題已答覆,但我的問題依然存在! :)我怎樣才能構建這個詞典並與整個應用程序共享,而不需要構建每個請求? (不完全是'如何',因爲你已經顯示出來了)我應該在哪裏編寫這個字典? –

相關問題