XPath匹配空格分隔的属性值?

时间:2014-08-26 00:13:09

标签: xml xpath

我有一个XML:

<entities>
  <entity attribute="attribute-value-1 attribute-value-2">value1</entity>
  <entity attribute="attribute-value-5 attribute-value-7 attribute-value-8">value2</entity>
</entities>

如何使用XPath选择属性值为"attribute-value-7"的实体?​​

1 个答案:

答案 0 :(得分:3)

你必须小心避免无意中匹配超弦,例如&#34; attribute-value-77&#34;或&#34; wrong-attribute-value-7&#34;。

使用常用于匹配HTML @class属性的惯用语:

XPath 1.0

//entity[contains(concat(' ', normalize-space(@attribute), ' '),
                           ' attribute-value-7 ')]

XPath 2.0

//entity[tokenize(@attribute,'\s+')='attribute-value-7']