【问题标题】:string concatenate multiple attribute values in xpath in c#字符串在c#中的xpath中连接多个属性值
【发布时间】:2013-06-06 23:25:08
【问题描述】:

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

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

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

谢谢。

【问题讨论】:

    标签: c# xpath xpathnavigator


    【解决方案1】:

    这样的事情应该没问题:

    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 中有一个更好的选择,带有 string-join,但不确定它是否在 .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);
    

    【讨论】:

    • 不幸的是,我正在处理一个只接受表达式进行评估的 api。不要认为字符串连接是在 .net 中实现的
    • 如果你事先不知道节点的数量,那就很难了。您可以根据节点的数量动态构建 xpath 表达式(请参阅我的编辑)
    猜你喜欢
    • 1970-01-01
    • 2017-08-25
    • 1970-01-01
    • 2015-06-21
    • 2011-05-18
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多