首页 > 解决方案 > XSLT:如何查看嵌套元素

问题描述

那是我需要应用 xslt 的 xml:

<document>
  <component>
    <structuredBody>
      <component>
        <section>
          <identifier code="S001"/>
          <...>
        </section>
        
      </component>
    </structuredBody>
  </component>
</document>

如您所见,这里有很多我不需要的嵌套结构。

我只需要section在哪里偷看元素section>identifier.code = "S001"

我想在不考虑上部结构的情况下查看我想要的元素。

我正在使用这个 xslt 但它没有偷看我想要的section元素:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
  <xsl:value-of select="//section[identifier/@code = 'S001']"/>
</xsl:template>
</xsl:stylesheet>

但我得到:

<?xml version="1.0" encoding="UTF-8"?>

上面的例子是为了简化我的问题而减少的努力:

<document>
  <component>
    <structuredBody>
      <component>
        <section>
          <identifier code="S001"/>
          <table>
            <tbody>
              <tr>
                <td>attribute1</td>
                <td>value1</td>
              </tr>
              <tr>
                <td>attribute2</td>
                <td>value2</td>
              </tr>
              <tr>
                <td>attribute3</td>
                <td>value3</td>
              </tr>
            </tbody>
          </table>
        </section>
        <section>
          <identifier code="S002"/>
          <table>
          ...
          </table>
        </section>
        
      </component>
    </structuredBody>
  </component>
</document>

我真正需要的是得到类似的东西:

<person> <!-- -> section-->
  <attribute key="attribute1">value1</attribute>
  <attribute key="attribute2">value2</attribute>
  <attribute key="attribute3">value3</attribute>
</person>

有任何想法吗?

标签: xslt

解决方案


尝试:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>

  <xsl:template match="/">
    <xsl:for-each select="//section[identifier/@code='S001']">
      <person>
        <xsl:for-each select="//td[1]">
          <attribute key="{.}"><xsl:value-of select="../td[2]"/></attribute>
        </xsl:for-each>   
      </person>
    </xsl:for-each>
  </xsl:template>

</xsl:stylesheet>

备注:这是已编辑帖子的解决方案。


推荐阅读