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

Dal*_*ale 3 xml xslt foreach value-of

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

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

<parent>
  <child>1</child>
  <child>2</child>
  <child>3</child>
</parent>
Run Code Online (Sandbox Code Playgroud)

我尝试使用xsl解析它:

<xsl:for-each select="parent">
  <print><xsl:value-of select="child"></print>
Run Code Online (Sandbox Code Playgroud)

想要这样的东西:

<print>1</print>
<print>2</print>
<print>3</print>
Run Code Online (Sandbox Code Playgroud)

但是我得到了这个:

<print>1</print>
Run Code Online (Sandbox Code Playgroud)

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

<parent>
  <child>1</child>
<parent>
</parent
  <child>2</child>
<parent>
</parent
  <child>3</child>
</parent
Run Code Online (Sandbox Code Playgroud)

反正有没有像上面那样格式化所需的打印输出,而是第一种方式?

谢谢

Dan*_*ley 5

这是因为你在做xsl:for-each父母而不是孩子.如果你把它改成这个(假设当前的上下文是/),你会得到你正在寻找的结果:

<xsl:for-each select="parent/child">
  <print><xsl:value-of select="."/></print>
</xsl:for-each>
Run Code Online (Sandbox Code Playgroud)

然而......使用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>
Run Code Online (Sandbox Code Playgroud)

这个样式表的输出将是:

<print>1</print>
<print>2</print>
<print>3</print>
Run Code Online (Sandbox Code Playgroud)