使用XSLT / XSL解析具有相同名称的子元素的XML

时间:2011-07-06 23:28:58

标签: xml xslt foreach value-of

我想知道是否有办法使用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

无论如何都没有像上面那样格式化所需的打印输出,而是第一种方式?

由于

1 个答案:

答案 0 :(得分: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>