XSLT/Xpath Select 元素基于两个属性的值

XSLT/Xpath Select elements based on the values of two attributes

我希望 return 所有 <nodes> 具有属性 k=network & v=LU 的标签。注意 LU 可以是字符串的一部分。 XML 只是 return 的列表 <tag k="network" v="LU"/>

如果我还有其他可以改进的地方,请注明。

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0"> 
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="osm">
    <xsl:copy>
      <xsl:apply-templates select="node/tag[@k='network' and @v='LU']"/>
    </xsl:copy>
  </xsl:template>

原文XML:

<osm>
   <node>
      <tag k="railway" v="station"/>
      <tag k="network" v="LU"/>
   </node>
   <node>
      <tag k="railway" v="station"/>
      <tag k="network" v="NR"/>
      <tag k="operator" v="LU"/>
   </node>
   <node>
      <tag k="railway" v="station"/>
      <tag k="network" v="NR,LU"/>
      <tag k="operator" v="LU"/>
   </node>
     <...snip...>
</osm>

期望的输出

<osm>
   <node>
      <tag k="railway" v="station"/>
      <tag k="network" v="LU"/>
   </node>
   <node>
      <tag k="railway" v="station"/>
      <tag k="network" v="NR,LU"/>
      <tag k="operator" v="LU"/>
   </node>
</osm>

我是否认为您的要求是 select 并复制所有 <node> 元素,这些元素的子 <tag> 元素具有属性 @k='network' 和属性 @v 这是包含令牌 LU?

的令牌列表

我会简单地这样做

<xsl:template match="osm">
  <osm>
    <xsl:copy-of select="node[tag[@k='network'][contains(@v,'LU')]]"/>
  </osm>
</xsl:template>

但是 contains() 测试可能需要更精确,例如,如果可以出现 v="LUCKY" 这样的值。对于 XSLT 2.0,我将使用谓词 [tokenize(@v, ',')='LU']