xslt node-set use in key function - find children by parent attribute

前端 未结 1 860
情书的邮戳
情书的邮戳 2021-01-27 06:11

I have an XML File.


   
    
        
              


        
相关标签:
1条回答
  • 2021-01-27 06:34

    Although this is not simple, I think you are making it much more complicated than it needs to be. Try the following stylesheet (not tested very thoroughly):

    XSLT 1.0

    <?xml version="1.0" encoding="UTF-8"?>
    <xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">
    
    <xsl:strip-space elements="*"/>
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
    
    <xsl:variable name="Items">
        <Item ID="answer">newid_answer</Item>
        <Item ID="number">newid_number</Item>
    </xsl:variable>
    
    <xsl:key name="ItemDef-by-ID" match="ItemDef" use="@ID"/>
    <xsl:key name="EnumItem-by-EID" match="EnumItem" use="@EID"/>
    
    <xsl:variable name="xml" select="/"/>
    
    <xsl:template match="/XML">
        <xsl:copy>
            <Items>
                <xsl:copy-of select="$Items" /> 
            </Items>
            <xsl:apply-templates select="exsl:node-set($Items)/Item"/>
        </xsl:copy>
    </xsl:template>
    
    <xsl:template match="Item">
        <xsl:variable name="item-id" select="@ID"/>
    
        <xsl:variable name="EnumItemRef">
            <xsl:for-each select="$xml">
                <xsl:copy-of select="key('ItemDef-by-ID', $item-id)/EnumItemRef"/>
            </xsl:for-each>
        </xsl:variable>
    
        <xsl:variable name="EID" select="exsl:node-set($EnumItemRef)/EnumItemRef/@EID"/>
    
        <ItemDef ID="{.}">
            <xsl:copy-of select="$EnumItemRef"/>
        </ItemDef>
        <xsl:for-each select="$xml">
            <xsl:copy-of select="key('EnumItem-by-EID', $EID)"/>
        </xsl:for-each>
    </xsl:template>
    
    </xsl:stylesheet>
    

    Note: when you are in the context of a node-set created by the exslt:node-set() function, you cannot use a key() to lookup data in the source XML document, unless you switch the context to the source document first.

    0 讨论(0)
提交回复
热议问题