xslt 1.0使属性成为父节点

时间:2016-04-01 13:11:35

标签: xml xslt xpath xslt-1.0

我需要转换下面的代码:

<test>
 <employee department="HR">john</employee>
 <intern department="HR">Jack</intern>
 <employee  department="HR">Jill</employee>
 <intern department="IT">Joe</intern>
 <employee department="IT">janet</employee>
 <intern department="IT">Jix</intern>
</test>

并使其看起来像以下

<test>
  <department id="HR">
    <employee department="HR">john</employee>
    <intern department="HR">Jack</intern>
    <employee department="HR">Jill</employee>
  </department>
  <department id="IT">
    <intern department="IT">Joe</intern>
    <employee department="IT">janet</employee>
    <intern department="IT">Jix</intern>
  </department>
</test>

我需要使用XSLT 1.0

1 个答案:

答案 0 :(得分:1)

使用这样的有效xml:

<test>
 <employee department="HR">john</employee>
 <intern department="HR">Jack</intern>
 <employee  department="HR">Jill</employee>
 <intern department="IT">Joe</intern>
 <employee department="IT">janet</employee>
 <intern department="IT">Jix</intern>
</test>

然后两个小模板Muenchian Method和一个密钥将执行:

<xsl:stylesheet version="1.0"
        xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:key  name="kdepartment" match="test/*[@department]" use="@department"/>
    <xsl:strip-space elements="*"/>

    <xsl:template match="@* | node()">
        <xsl:copy>
            <xsl:apply-templates select="@* | node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match="test">
        <xsl:copy>
            <xsl:for-each select="*[@department][count(. | key('kdepartment', ./@department)[1]) = 1]">
                <xsl:variable name="this" select="." />
                <department id="{./@department}">
                    <xsl:for-each select="key('kdepartment', $this/@department) ">
                        <xsl:apply-templates select="." />
                    </xsl:for-each>
                </department>
        </xsl:for-each>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

获得此输出:

<test>
  <department id="HR">
    <employee department="HR">john</employee>
    <intern department="HR">Jack</intern>
    <employee department="HR">Jill</employee>
  </department>
  <department id="IT">
    <intern department="IT">Joe</intern>
    <employee department="IT">janet</employee>
    <intern department="IT">Jix</intern>
  </department>