3

我想知道是否有一种方法可以使用 XSLT 传递具有相同元素名称的所有子元素的父元素。

例如,如果原始的xml文件是这样的:

<parent>
  <child>1</child>
  <child>2</child>
  <child>3</child>
</parent>

我尝试使用 xsl 解析它:

<xsl:for-each select="parent">
  <print><xsl:value-of select="child"></print>

想要这样的东西:

<print>1</print>
<print>2</print>
<print>3</print>

但我明白了:

<print>1</print>

因为 for-each 更适合这种格式:

<parent>
  <child>1</child>
<parent>
</parent
  <child>2</child>
<parent>
</parent
  <child>3</child>
</parent

无论如何都可以获得所需的打印输出而不像上面那样格式化它,而是第一种方式?

谢谢

4

1 回答 1

5

这是因为你正在xsl:for-each对父母而不是孩子做。如果将其更改为此(假设当前上下文为 ),您将获得所需的结果/

<xsl:for-each select="parent/child">
  <print><xsl:value-of select="."/></print>
</xsl:for-each>

但是......xsl:for-each通常不需要使用您应该让覆盖模板为您处理工作,而不是尝试从单个模板/上下文(如/

这是一个完整的示例样式表:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="parent">
    <xsl:apply-templates/>
  </xsl:template>

  <xsl:template match="child">
      <print><xsl:apply-templates/></print>
  </xsl:template>

</xsl:stylesheet>

此样式表的输出将是:

<print>1</print>
<print>2</print>
<print>3</print>
于 2011-07-06T23:43:26.167 回答