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

问题描述:

我想知道是否有方法通过使用XSLT具有相同元素名称的所有子元素通过父元素进行传输。使用XSLT/XSL解析具有相同名称的子元素

例如,如果原始的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> 

因为换各自更专为这种格式:

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

反正是有以获得所需的打印输出,不进行格式化它喜欢它的正上方,而第一种方式?

感谢

这是因为你在做父,而不是孩子的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>