字符串在c#中的xpath中连接多个属性值

时间:2013-06-06 23:25:08

标签: c# xpath xpathnavigator

是否有一个xpath表达式可用于连接多个属性值并与XPathNavigator.Evaluate一起使用

    <root>
      <node class="string"></node>
      <node class="join"></node>
    </root>

    XPathNavigator.Evaluate(<expression>) 
    should return a string with value string;join

感谢。

1 个答案:

答案 0 :(得分:0)

这样的事情应该没问题:

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);

使用 string-join 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);
相关问题