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

标签 c# xpath xpathnavigator

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

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

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

谢谢。

最佳答案

这样的事情应该没问题:

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

关于c# - 字符串在c#中的xpath中连接多个属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16973853/

相关文章:

c# - 在 C# 中将方法隐式转换为 Func

c# - 将 Redis 与 C# : value is not an integer or out of range, sPort : 51410, LastCommand 一起使用时出错:

c# - 在 Win7 64 位上以编程方式从 C# 中的 ftp 下载文件时访问路径被拒绝

java - 使用 Java for 循环中的 Xpath

xml - 如何使用Xpath(using XSLT)查询遍历回XML文件中的父节点?

c# - 用于选择特定节点下的节点(中间有零个或多个节点)的 XPath

c# - 将扩展方法中的事件和函数分配为参数

xml - 如何从 XPath 中的标记中选择一个未知层数的节点?

c# - XPathNavigator 是否需要 MoveToParent()/MoveToFirstChild() 对?

html - xPath/HTML : Select node based on related node