使用XSLT组合来自不同节点的值

时间:2015-11-28 09:21:03

标签: xml xslt

从以下XML中我想组合具有相同引用ID的值:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
    <cd id="01">
        <reference id="01"/>
        <title>Empire Burlesque</title>
    </cd>
    <cd id="01">
        <reference id="02"/>
        <title>Hide your heart</title>
    </cd>
    <cd id="01">
        <reference id="03"/>
        <title>Greatest Hits</title>
    </cd>
    <cd id="01">
        <reference id="04"/>
        <title>Still got the blues</title>
    </cd>
    <cd id="02">
        <reference id="01"/>
        <value>In stock</value>
    </cd>
    <cd id="02">
        <reference id="02"/>
        <value>Out of stock</value>
    </cd>
    <cd id="02">
        <reference id="03"/>
        <value>Out of stock</value>
    </cd>
    <cd id="02">
        <reference id="04"/>
        <value>In stock</value>
    </cd>
</catalog>

结果必须是这样的:

<cd reference="01" title-cd="Empire Burlesque" stock="In stock"/>
<cd reference="02" title-cd="Hide your heart" stock="Out of stock"/>
<cd reference="03" title-cd="Greatest hits" stock="Out of stock"/>
<cd reference="04" title-cd="Still got the blues" stock="In stock"/>

如何使用XSLT 1.0实现这一目标?

亲切的问候,Sjoerd

1 个答案:

答案 0 :(得分:0)

这个例子似乎有点人为。无论如何,解决交叉引用的最佳方法是使用key

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:key name="stock" match="cd[@id='02']" use="reference/@id" />

<xsl:template match="/catalog">
    <xsl:copy>
        <xsl:for-each select="cd[@id='01']">
            <cd reference="{reference/@id}" title-cd="{title}" stock="{key('stock', reference/@id)/value}"/>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

应用于您的输入示例,结果将是:

<?xml version="1.0" encoding="UTF-8"?>
<catalog>
   <cd reference="01" title-cd="Empire Burlesque" stock="In stock"/>
   <cd reference="02" title-cd="Hide your heart" stock="Out of stock"/>
   <cd reference="03" title-cd="Greatest Hits" stock="Out of stock"/>
   <cd reference="04" title-cd="Still got the blues" stock="In stock"/>
</catalog>