XPATH以字符串结尾的属性值



我在选择具有以一定值结尾的元素的元素时遇到了麻烦。

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

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

首先要注意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']

如果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>

最新更新