XPath:如何 select 具有一个或另一个属性的所有元素

XPath: How to select all elements which have one attribute or another

我到处都在寻找这个,但找不到解决我问题的方法。我试图找到一个 XPath 表达式,它将 select 所有具有名为 "user" 或 "product"(或两者)的属性的元素。我知道一个属性的 XPath 表达式是:

//*[@user]

//*[@product]

这两种方法都可以正常工作,它们可以抓取文档中任意位置具有适当属性的所有元素。但是每当我尝试将它们组合在一起时:

//*[@user|@product]

//*[@user]|//*[@product]

我只获取在找到这些属性的第一级中找到的元素。这是我的 XML 文档的示例:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<?xml-stylesheet href="xslt.xml" type="application/xml"?>
<catalog>
<item user="me" product="coffee" />
<price product="expensive" quality="good">.50</price>
<item user="still me"><note product="poison">Do not eat.</note></item>
<price product="mystery"><exchange user="still me" product="euro" />.95</price>
</catalog>

现在有了这个 XSLT 转换:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="//*[@user|@product]">
<xsl:copy />
</xsl:template>
</xsl:stylesheet>

我只得到这些元素:

<item/>
<price/>
<item/>
<price/>

但我真正想要的是:

<item/>
<price/>
<item/>
<note/>
<price/>
<exchange/>

当然,正如您可能已经猜到的那样,当我将 "user" 属性放入我的目录元素时,selected 的只是目录元素,没有子元素。

我已经尝试了几个小时,但找不到解决方案。如果有人知道如何解决这个问题,请告诉我。

使用 or 而不是 || 是一个不同的运算符,坦率地说我不知道​​ :-)

的含义

尽管 Jiří Kantor 提供的答案是正确的,但您必须使用以下 XSLT 才能获得所需的结果:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
    <xsl:apply-templates select="//*[@user or @product]"/>
</xsl:template>

<xsl:template match="*">
    <xsl:copy/>
</xsl:template>

</xsl:stylesheet>