-2

我有一个如下的 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,如果节点“A”中的文本包含键“12345”,我想选择节点“B”中的输出值

请提供用于实现此目的的 LINQ 查询的输入。

谢谢 !!

4

2 回答 2

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

于 2013-03-19T12:33:07.037 回答
0

或者与 LINQ 和 XPath 单行:

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

这将返回第一个找到的元素匹配条件的值。如果您需要所有匹配项,请改用XPathSelectElements

于 2013-03-19T12:39:23.580 回答