【问题标题】:XSL: get xml elements into another nodeXSL:将 xml 元素放入另一个节点
【发布时间】:2017-04-04 16:44:44
【问题描述】:

我有这个 xml,并且 xslt 转换有问题:

<start>
    <row>
        <xxx Caption="School1"></xxx>
        <yyy Caption="Subject1"></yyy>
        <zzz></zzz>
    </row>
    <row>
        <xxx Caption="School2"></xxx>
        <yyy Caption="Subject2"></yyy>
        <zzz></zzz>
    </row>
</start>

Xsl 转换是这样的:

<xsl:stylesheet>
    <xsl:output method="xml" indent="yes"/>

    <xsl:template match="/">
        <schools>
            <xsl:apply-templates select="//row/*" />
        </schools>
    </xsl:template>

    <xsl:template match="//row/*">
        <school>
            <xsl:if test="name()='xxx'">
                <name>
                    <xsl:value-of select="@Caption"/>
                </name>
            </xsl:if>
            <xsl:if test="name()='yyy'">
                <subject>
                    <xsl:value-of select="@Caption"/>
                </subject>
            </xsl:if>
        </school>
    </xsl:template>
</xsl:stylesheet>

xsl 转换给出了这个结果,这并不是我想要的结果:

<schools>
    <school>
        <name>School1</name>
    </school>
    <school>
        <subject>Subject1</subject>
    </school>
    <school />
    <school>
        <name>School2</name>
    </school>
    <school>
        <subject>Subject2</subject>
    </school>
    <school />
</schools>

我希望结果是这样的:

<schools>
    <school>
        <name>School1</name>
        <subject>Subject1</subject>
    </school>
    <school>
        <name>School2</name>
        <subject>Subject2</subject>
    </school>
</schools>

姓名和学科元素应该在同一个学校元素内。

请帮助我找到更好的解决方案。

【问题讨论】:

    标签: xslt


    【解决方案1】:

    你为什么不简单地做:

    XSLT 1.0

    <xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    <xsl:strip-space elements="*"/>
    
    <xsl:template match="/start">
        <schools>
            <xsl:apply-templates/>
        </schools>
    </xsl:template>
    
    <xsl:template match="row">
        <school>
            <xsl:apply-templates select="xxx | yyy"/>
        </school>
    </xsl:template>
    
    <xsl:template match="xxx">
        <name>
            <xsl:value-of select="@Caption"/>
        </name>
    </xsl:template>
    
    <xsl:template match="yyy">
        <subject>
            <xsl:value-of select="@Caption"/>
        </subject>
    </xsl:template>
    
    </xsl:stylesheet>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-21
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-26
      • 1970-01-01
      相关资源
      最近更新 更多