xsl copy if当前节点的属性等于另一个节点的属性

时间:2014-11-10 08:20:57

标签: xslt attributes copy

我有一个示例XML文件:

<?xml version="1.0" encoding="UTF-8"?>
<XML>
    <MetaData>
        <Ref MDID='ID'></Ref>
    </MetaData>
    <MetaData2>
        <Ref MDID='ID2'></Ref>
    </MetaData2>
    <Items ID='ID'>
        <Item OID='haveit'></Item>
        <Item OID='ornot'></Item>
    </Items>
    <Items ID= ID2'>
        <Item OID='ornot'></Item>
        <Item OID='ornot'></Item>
    </Items>
</XML>

我必须对其进行转换,以便收到以下结果。

<?xml version="1.0" encoding="UTF-8"?>
<XML>
    <MetaData>
        <Ref MDID='ID'></Ref>
    </MetaData>
    <Items ID='ID'>
        <Item OID='haveit'></Item>
    </Items>
</XML>

首先,我必须检查项目'hasit'是否存在。然后我复制相应的父“Item”。然后我需要复制MDID等于项目ID的MetaData(在这种情况下为'ID',但我不知道我的实例中的确切值) 到目前为止我所拥有的:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.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:variable name="Item" select = "'haveit'"/>
    <xsl:template match="XML">
        <xsl:copy>
            <xsl:apply-templates />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="Items">
        <xsl:if test="child::Item[@OID = $Item]">
            <xsl:copy>
                <xsl:copy-of select="@*" /> <!-- copy attributes -->                                            
            </xsl:copy>             
        </xsl:if>
    </xsl:template>
</xsl:stylesheet>

使用此代码,我可以复制我想要的项目和相应的项目元素。现在我不知道如何获得正确的MetaData元素。如何检查Ref的MDID是否与Items ID具有相同的值?

1 个答案:

答案 0 :(得分: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:param name="oid" select="'haveit'"/>

<xsl:key name="meta" match="*" use="Ref/@MDID" />

<xsl:template match="/XML">
    <xsl:variable name="matching-items" select="Items[Item/@OID=$oid]" />
    <xsl:copy>
        <xsl:copy-of select="key('meta', $matching-items/@ID)"/>
        <xsl:apply-templates select="$matching-items"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Items">
    <xsl:copy>
        <xsl:copy-of select="@*" />  
        <xsl:copy-of select="Item[@OID=$oid]" />                                         
    </xsl:copy>
</xsl:template>    

</xsl:stylesheet>
相关问题