连接 XPath 数组中的内部文本

Concatenating inner text in an XPath array

我有一些 XML 看起来像这样:

<root>
  <instructions type="array">
    <item type="string">Cannot do business directly with consumers</item>
    <item type="string">Cannot marry a martian</item>
  </instructions>
</root>

和一个如下所示的 instructions 变量:

var instructions = myXDocument.XPathSelectElements("/root/instructions").Nodes();

我正在尝试连接所有 item 字符串,因此:

"Cannot do business directly with consumers, Cannot marry a martian"

我目前的尝试是

instructions.Select(x => x.[[What do I put here?]]).Aggregate((i,j) => i + ", " + j)

但无法弄清楚如何从我的 lambda 表达式中的每个节点获取内部文本。 x.ToString() 产量 "<item type="string">Cannot do business directly with consumers</item>"

我知道这不是您要查找的 lambda 表达式,但这是获得结果输出的方法。

string result;
XElement root = XElement.Load(SomeXML);
root.Element("root").Elements("instructions").Elements("item").All<XElement>(xe =>
{
    result = result + xe.Attribute("type").Value),
    return true;
});

试试这个

var xml = "<root><instructions type=\"array\"><item type=\"string\">Cannot do business directly with consumers</item><item type=\"string\">Cannot marry a martian</item></instructions></root>";
var document = XDocument.Parse(xml);
var result = string.Join(", ", document.Descendants("instructions").Elements("item").Select(x=>x.Value));

输出:

Cannot do business directly with consumers, Cannot marry a martian

用同样的方法,只需将Nodes()替换为Elements(),然后访问返回的XElementsValue属性即可得到内部文本:

var instructions = myXDocument.XPathSelectElements("/root/instructions").Elements();
var result = instructions.Select(x => x.Value).Aggregate((i,j) => i + ", " + j);