2013-03-19 55 views
-2

我有如下一個XML取值:的LINQ to XML - 基於狀態

<Nodes> 
    <Node> 
    <A>This is a dummy text {12345}</A> 
    <B>Output Value</B> 
    </Node> 
    <Node> 
    <A>This is another dummy text {3462832}</A> 
    <B>Output Value</B> 
    </Node> 
</Nodes> 

我使用LINQ to XML,並希望選擇節點「B」的輸出值,如果在節點文本「 A'包含密鑰'12345'

請提供應用於實現此目的的LINQ查詢的輸入。

謝謝!

回答

3

這不正是你想要的: -

var nodes = from n in xml.Descendants("Node") 
         .Where(x => x.Element("A").Value.Contains("12345")) 
      select n.Element("B").Value; 

XML示例: -

<?xml version="1.0" encoding="utf-8"?> 
<Nodes> 
    <Node> 
     <A>This is a dummy text {12345}</A> 
     <B>Output Value</B> 
    </Node> 
    <Node> 
     <A>This is a dummy text {12345}</A> 
     <B>Output Value 2</B> 
    </Node> 
    <Node> 
     <A>This is another dummy text {3462832}</A> 
     <B>Output Value</B> 
    </Node> 
</Nodes> 

返回結果: -

Output Value Output Value 2

+0

謝謝!有效。我沒有適當地使用lambda表達式。 – 2013-03-19 13:04:52

+0

沒問題。如果這回答你的問題,那麼請考慮[接受它作爲一個答案](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work),以幫助其他用戶可能面臨一個類似的問題。 – DGibbs 2013-03-19 13:07:49

0

或與單行LINQ和XPath:

XDocument xdoc = XDocument.Load(path_to_xml); 
var b = (string)xdoc.XPathSelectElement("//Node[contains(A,'12345')]/B"); 

返回首次找到的元素匹配條件的值。如果您需要所有匹配項,請改爲使用XPathSelectElements