【问题标题】:XPath for attribute value that ends with a string?以字符串结尾的属性值的 XPath?
【发布时间】:2018-02-18 15:14:24
【问题描述】:

我在选择属性以特定值结尾的元素时遇到问题。

XML 看起来像

<root>
<object name="1_2"><attribute name="show" value="example"></object>
<object name="1_1"><attribute name="show" value="example"></object>
<object name="2_1"><attribute name="show" value="example"></object>
</root>

所以我需要从以_1 结尾的对象中的属性中提取所有值,我该怎么做?

我做了这段代码

 XmlNodeList childnodes = xRoot.SelectNodes("//Object[@Name='1_1']");
        foreach (XmlNode n in childnodes)
            Console.WriteLine(n.SelectSingleNode("Attribute[@Name='show']").OuterXml);

但我找不到如何搜索属性名称部分以及如何获取目标参数的确切值。

【问题讨论】:

    标签: c# xml xpath


    【解决方案1】:

    首先请注意,XML 和 XPath 区分大小写,因此 Objectobject 不同,Namename 不同。

    XPath 2.0

    这个 XPath 2.0 表达式,

    //object[ends-with(@name,'_1')]
    

    将选择所有name 属性值以_1 结尾的object 元素。

    XPath 1.0

    XPath 1.0 缺少 ends-with() 函数,但可以通过更多的工作实现相同的结果:

    ends-with($s, $e) ≡ (substring($s, string-length($s) - string-length($e) +1) = $e)
    

    适用于$s@name$e'_1' 的情况,上面简化为这个表达式:

    //object[substring(@name, string-length(@name) - 1) = '_1']
    

    【讨论】:

    • XPath 1.0 语法不正确。 string-length(@name) 重复。它应该是//object[substring(@name, string-length(@name) - 1) = '_1'],因为@jan-peter-vos 在另一个答案中有它。
    • @Metalogic:你是对的。接得好!已更新答案以修复该错误并添加有关如何在 XPath 1.0 中执行 ends-with() 的说明。谢谢。
    【解决方案2】:

    如果C# 支持XPath 2.0 你应该可以使用:

    XmlNodeList childnodes = xRoot.SelectNodes("//object[ends-with(@name, '_1')]");
    

    如果不是,那么稍长的版本应该可以工作:

    XmlNodeList childnodes = xRoot.SelectNodes("//object[substring(@name, string-length(@name) - 1) = '_1']");
    

    此外,您的 xml 无效,因为您需要关闭 attribute 元素:

    <root>
      <object name="1_2"><attribute name="show" value="example"/></object>
      <object name="1_1"><attribute name="show" value="example"/></object>
      <object name="2_1"><attribute name="show" value="example"/></object>
    </root>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-12
      • 2015-05-22
      • 2019-03-15
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      相关资源
      最近更新 更多