0
votes

For XML Transformation, i have to transform XML in such a way in adds counter value to all child node attribute Below is my xml sample

<hs>
            <hscode>
                    <hsdetail>
                        <Name>Shirt</Name>
                        <ItemPrice>30</ItemPrice>
                    </hsdetail>
                    <hsdetail>
                        <Name>Shirt</Name>
                        <ItemPrice>30</ItemPrice>
                    </hsdetail>
                </hscode>
        </hs>

Using Xslt i want to apply counter on each child nodes of , id there are multiple hsdetails, each attribute in this node will use counter, and so on, Theconverted xml looks like below

<hs>
    <hscode>
        <hsdetail>
            <Name1>Shirt</Name1>
            <ItemPrice1>30</ItemPrice1>
        </hsdetail>
        <hsdetail>
            <Name2>Shirt</Name2>
            <ItemPrice2>30</ItemPrice2>
        </hsdetail>
    </hscode>
</hs>

I am using xsl but does not seems to be working when applying transformation Any help on this? The xsl is as follows:

<xsl:stylesheet xmlns:xsl="w3.org/1999/XSL/Transform" version="1.0"> 
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="hsdetail/*">
        <xsl:element
            name="{name()}{count(preceding-sibling::*[name() = name(current())]) + 1}">
            <xsl:apply-templates select="@*|node()" />
    </xsl:element>
</xsl:template> </xsl:stylesheet>
1
Please show what have you attempted so far and how does it not workingAndreas
<xsl:stylesheet xmlns:xsl="w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="@*|node()"> <xsl:copy><xsl:apply-templates select="@*|node()" /></xsl:copy> </xsl:template> <xsl:template match="hsdetail/*"> <xsl:element name="{name()}{count(preceding-sibling::*[name() = name(current())]) + 1}"> <xsl:apply-templates select="@*|node()" /> </xsl:element> </xsl:template> </xsl:stylesheet>John gotham
Hi Andreas, i am using this xsltJohn gotham

1 Answers

0
votes

How about:

XSLT 1.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="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="hsdetail">
    <xsl:variable name="i" select="position()" />
    <xsl:copy>
        <xsl:for-each select="*">
            <xsl:element name="{name()}{$i}">
                <xsl:apply-templates select="@*|node()"/>
            </xsl:element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>