XSLT:如何在高度嵌套的XML中基于依赖于其子标记值的条件获取父标记的值

时间:2017-04-03 09:44:08

标签: xml xslt

我一直在尝试为此获得解决方案,但仍无法找到合适的解决方案。 我引用了几个链接Nested for-each loops, accessing outer element with variable from the inner loopHow to extract child tags text and extended text of parent tag from xml using xslt,但这些问题没有嵌套标记。

我的XML:

<catalog title="TitleABC1">
  <cd>
    <title code="Y">Picture book</title>
    <artist>Simply Red</artist>
    <country>EU</country>
  </cd>
  <catalog title="TitleABC2">
    <cd>
      <cd>
        <title code="N">Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
      </cd>
    </cd>
    <cd>
      <cd>
        <cd>
          <title code="Y">Hide your heart</title>
          <artist>Bonnie Tyler</artist>
          <country>UK</country>
        </cd>
      </cd>
    </cd>
    <cd>
      <catalog title="TitleABC3">
        <cd>
          <title code="N">Red</title>
          <artist>The Communards</artist>
          <country>UK</country>
        </cd>
      </catalog>
    </cd>
    <cd>
      <title code="N">Unchain my heart</title>
      <artist>Joe Cocker</artist>
      <country>USA</country>
    </cd>
  </catalog>
</catalog>

对于上述XML,条件是,如果任何子/后代catalog标记的代码属性为“Y”,则仅显示那些title标记的标题。

因此,输出应该像:

TitleABC1
TitleABC2

我正在尝试使用以下XSLT逻辑,但无法获得所需的解决方案。

 <xsl:template match="catalog">
<!-- Store the value in a variable -->
              <xsl:for-each select="//title">
<!-- <xsl:if> to check for the code attrib -->                                                 
              </xsl:for-each>
            </xsl:template>

1 个答案:

答案 0 :(得分:1)

  

只有那些catalog标签才会被显示   子/后代title代码的代码属性为&#39; Y&#39;。

为什么不完全按照你所说的去做:

XSLT 1.0

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

<xsl:template match="/">
    <xsl:for-each select="//catalog[descendant::title/@code='Y']">
        <xsl:value-of select="@title" />
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>

</xsl:stylesheet>

或者,如果您更喜欢递归方法:

XSLT 1.0

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

<xsl:template match="catalog[descendant::title/@code='Y']">
    <xsl:value-of select="@title" />
    <xsl:text>&#10;</xsl:text>
    <xsl:apply-templates select="*"/>
</xsl:template>

<xsl:template match="text()"/>

</xsl:stylesheet>

您需要了解built-in template rules以了解其工作原理。

相关问题