来自excel的xml具有3个相同的组 - 转换为一个重复组

时间:2011-05-03 15:35:06

标签: xml excel xslt

我是XML和XSLT的新手。我在论坛中搜索了类似的东西,没有成功。 XSLT可以进行以下翻译吗?它基本上是一个从Excel电子表格派生而来的XML,它有3个在同一行上重复相同的组,因此它们有不同的名称,group1,... 2和... 3,我想将它们组成一个组重复3次,如果它们中有数据。以下示例是简化版本:

<application> 
    <group1>
        <name1>John</name1>
    </group1>
    <group2>
        <name2>Mary</name2>
    </group2>
    <group3>
        <name3>Peter</name3>
    </group3>
</application> 

转换为

<application> 
    <group ref="001">
        <line_no>001</line_no>
        <name>John</name>
    </group>
    <group ref="002">
        <line_no>002</line_no>
        <name>Mary</name>
    </group>
    <group ref="003">
        <line_no>003</line_no>
        <name>Peter</name>
    </group>
</application> 

Excel不会以最简单的方式导出到XML。

2 个答案:

答案 0 :(得分:0)

Xslt具有position()功能。这可以帮助您获得名称前面的数字。

希望这有帮助。

答案 1 :(得分:0)

一个样式表可能是:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>
    <xsl:template match="*[starts-with(name(),'group')]">
        <group ref="{format-number(substring-after(name(),'group'),'000')}">
            <xsl:apply-templates/>
        </group>
    </xsl:template>
    <xsl:template match="*[starts-with(name(),'name')]">
        <line_no>
            <xsl:value-of
             select="format-number(substring-after(name(),'name'),'000')"/>
        </line_no>
        <name>
            <xsl:apply-templates/>
        </name>
    </xsl:template>
</xsl:stylesheet>

输出:

<application>
    <group ref="001">
        <line_no>001</line_no>
        <name>John</name>
    </group>
    <group ref="002">
        <line_no>002</line_no>
        <name>Mary</name>
    </group>
    <group ref="003">
        <line_no>003</line_no>
        <name>Peter</name>
    </group>
</application>