这样的事情应该没问题:
var document = XDocument.Parse(s);
var res = (document.Root.XPathEvaluate("/root/node/@class") as IEnumerable).Cast<XAttribute>().Aggregate("", (a, c) => a + ";" + c.Value);
res = res.Substring(1);
XPath 2.0中有一个更好的选择,带有字符串连接,但不确定它是否在 .Net 中实现...
编辑:否则动态构建 XPath 表达式:
int count = (document.Root.XPathEvaluate("/root/node") as IEnumerable).Cast<XNode>().Count();
string xpath = "concat(";
for (int i = 1; i <= count; ++i)
{
xpath += "/root/node[" + i + "]/@class";
if (i < count)
{
xpath += ", ';',";
}
else
{
xpath += ")";
}
}
var res = document.Root.XPathEvaluate(xpath);