Adrian
Adrian

Reputation: 2656

Create new node based on id from another xml, loop

I would like to add a node based on , but the problem is the categories are in a separate file and moreover I would like to loop to find all based on .

Let me show an example:

category.xml:

<ROOT>
<GROUPITEM>
<G_ID>1368</G_ID>
<GROUP>Phone</GROUP>
<PARENT>0</PARENT>
</GROUPITEM>

<GROUPITEM>
<G_ID>1194</G_ID>
<GROUP>Apple</GROUP>
<PARENT>1368</PARENT>
</GROUPITEM>

<GROUPITEM>
<G_ID>1195</G_ID>
<GROUP>2019</GROUP>
<PARENT>1194</PARENT>
</GROUPITEM>
</ROOT>

item.xml:

<ROOT>
<SHOPITEM>
    <PRODUCT_ID>96555</PRODUCT_ID>
    <GROUP_ID>1195</GROUP_ID>
    <PRODUCT_NAME>Apple iPhone 8 Plus</PRODUCT_NAME>
</SHOPITEM>
</ROOT>

Example output:

<ROOT>
<SHOPITEM>
    <PRODUCT_ID>96555</PRODUCT_ID>
    <GROUP_ID>1195</GROUP_ID>
    <PRODUCT_NAME>Apple iPhone 8 Plus</PRODUCT_NAME>
    <CATEGORY>Phone | Apple | 2019</CATEGORY>
</SHOPITEM>
</ROOT>

In simple words I am looking for a way to create node (in item.xml) and add here value ( from category.xml) based on (item.xml): search in category.xml for the same -> if found, add it -> search more based on (if success add separator + value) -> loop.

Upvotes: 0

Views: 27

Answers (1)

michael.hor257k
michael.hor257k

Reputation: 117165

Try something like (untested):

XSLT 2.0

<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:key name="group" match="GROUPITEM" use="G_ID" />

<xsl:template match="SHOPITEM">
    <xsl:copy>
        <xsl:copy-of select="*"/>
        <CATEGORY>
            <xsl:apply-templates select="key('group', GROUP_ID, document('category.xml'))"/>
        </CATEGORY>
    </xsl:copy>
</xsl:template>

<xsl:template match="GROUPITEM">
    <xsl:variable name="parent" select="key('group', PARENT)" />
    <xsl:if test="$parent">
        <xsl:apply-templates select="$parent"/>
        <xsl:text> | </xsl:text>
    </xsl:if>
    <xsl:value-of select="GROUP"/>
</xsl:template>

</xsl:stylesheet>

Upvotes: 1

Related Questions