[xsl] Match Parents Element ID

Subject: [xsl] Match Parents Element ID
From: "Byomokesh Sahoo sahoo.byomokesh@xxxxxxxxx" <xsl-list-service@xxxxxxxxxxxxxxxxxxxxxx>
Date: Mon, 27 Jan 2025 08:58:10 -0000
Hi,

We have multiple XML files which need to fetch parent elements with
attributes only from one file. Find below my xsl and input files.

ID File: <!-- Take chapter based on the section file -->
<gd id="RB_A">
        <act id="RB_C">
            <title>SET</title>
            <body>
                <chap id="RB_CHAP1">
                    <sect id="RB_S1"/>
                    <sect id="RB_S2"/>
                </chap>
                <chap id="RB_CHAP2">
                    <sect id="RB_S3"/>
                    <sect id="RB_S4"/>
                </chap>
            </body>
        </act>
    </gd>
Sect file: <!-- Multiple Section file like this -->
 <sce>
        <gd id="RB_A">
            <act id="RB_C">
                <title>TITLE</title>
                <body>
                    <sect id="RB_S1">
                    <title>Tile</title>
                    <p>Paragrph</p>
                    </sect>
                </body>
            </act>
        </gd>
    </sce>
Desired File:
 <sce>
        <gd id="RB_A">
            <act id="RB_C">
                <title>TITLE</title>
                <body>
                    <chap id="RB_CHAP1">
                    <sect id="RB_S1">
                    <title>Title</title>
                    <p>Paragraph</p>
                    </sect>
                    </chap>
                </body>
            </act>
        </gd>
    </sce>

XSL:


<xsl:transform version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform
">
    <xsl:output method="xml" version="1.0" encoding="ISO-8859-1"
indent="yes" />
    <xsl:variable name="ch" select="'ID.xml'" />
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>

    <xsl:template match="sce/gd/act/body">
        <xsl:variable name="info"
select="document($ch)//sce/gd/act/body/chap/sect[@id=current()/@id]/." />
        <chap id="">
            <xsl:attribute name="id">
                <xsl:value-of select="$info[parent::chap[@id]]"/>
            </xsl:attribute>
            <xsl:copy>
                <xsl:apply-templates select="@*|node()" />
                <xsl:for-each select="$info/*">
                        <xsl:copy-of select="." />
                </xsl:for-each>
            </xsl:copy>
        </chap>
    </xsl:template>
</xsl:transform>


Thanks

Current Thread