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



I have an XML File.



<?xml version="1.0" encoding="UTF-8"?>
<XML>
<Items>
<ItemRef ID='answer'></ItemRef>
<ItemRef ID='number'></ItemRef>
<ItemRef ID='delete'></ItemRef>
<ItemRef ID='remove'></ItemRef>
</Items>
<ItemDef ID='anwser'></ItemDef>
<ItemDef ID='number'>
<EnumItemRef EID = '1'></EnumItemRef>
</ItemDef>
<ItemDef ID='delete'>
<EnumItemRef EID = '2'></EnumItemRef>
</ItemDef>
<ItemDef ID='remove'></ItemDef>
<EnumItem EID="1">
<EnumItem Value = '1'></EnumItem>
<EnumItem Value = '2'></EnumItem>
<EnumItem Value = '3'></EnumItem>
</EnumItem>
<EnumItem EID="2">
<EnumItem Value = 'yes'></EnumItem>
<EnumItem Value = 'no'></EnumItem>
</EnumItem>
</XML>


what I need to transform into a XML file like this:



<?xml version="1.0" encoding="UTF-8"?>
<XML>
<Items>
<ItemRef ID='newid_answer'></ItemRef>
<ItemRef ID='newid_number'></ItemRef>
</Items>
<ItemDef ID='newid_answer'></ItemDef>
<ItemDef ID='newid_number'>
<EnumItemRef EID = '1'></EnumItemRef>
</ItemDef>
<EnumItem EID="1">
<EnumItem Value = '1'></EnumItem>
<EnumItem Value = '2'></EnumItem>
<EnumItem Value = '3'></EnumItem>
</EnumItem>
</XML>


I have following XSLT 1.0 file. With this I'm able to create the Items and ItemDefs I want. I'm just missing an idea how to find the corresonding EnumItemRef and EnumItem. Either I have to check if the current ItemDef has a child called EnumItemRef, or I could solve it with a key function (what would maybe be the better solution). I tried both but I can't make it work.



<xsl:variable name="Items">
<Item ID="answer">newid_answer</Item>
<Item ID="number">newid_number</Item>
</xsl:variable>

<xsl:key name="get_Enum_by_ID" match="/XML/ItemDef/EnumItemRef" use="/XML/ItemDef/@ID" />

<xsl:template match="XML">
<xsl:copy>
<xsl:apply-templates />
<xsl:call-template name="Items" />
<xsl:call-template name="ItemDef" />
</xsl:copy>
</xsl:template>

<xsl:template name="Items">
<xsl:element name="Items">
<xsl:for-each select="exslt:node-set($Items)/Item">
<xsl:element name="ItemRef">
<xsl:attribute name="ID"><xsl:value-of select="text()"/></xsl:attribute>
</xsl:element>
</xsl:for-each>
</xsl:element>
</xsl:template>

<xsl:template name="ItemDef">
<xsl:for-each select="exslt:node-set($Items)/Item">
<xsl:element name="ItemDef">
<xsl:attribute name="ID"><xsl:value-of select="text()" /></xsl:attribute>
</xsl:element>
<-- how can I find the corresponding EnumitemRef and EnumItem? -->
<xsl:copy-of select="key('get_Enum_by_ID', @ID)" />

</xsl:for-each>
</xsl:template>


I would be happy if anyone could give me an idea how to solve this.


No comments:

Post a Comment