Page 1 of 1

Adding an id-attribute to element

Posted: Wed Jul 12, 2017 11:53 am
by bee123
Hello,
I've got another newbie question.
How can I add an id-attribute with consecutive numbers in it in my xml.file.

It should look something like that:

<text id='1'>
<text id='2'>
<text id='3'>
<text id='4'>



Thank you!

Re: Adding an id-attribute to element

Posted: Wed Jul 12, 2017 12:33 pm
by Radu
Hi,

You could try to create an XSLT stylesheet like this:

Code: Select all

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="2.0">
   
    <!-- Copy anything as it is -->
    <xsl:template match="node() | @*">
        <xsl:copy>
            <xsl:apply-templates select="node() | @*"/>
        </xsl:copy>
    </xsl:template>
   
    <xsl:template match="text">
        <text>
            <xsl:apply-templates select="@*"/>
            <xsl:attribute name="id" select="count(preceding::text) + 1"/>
            <xsl:apply-templates select="node()"/>
        </text>
    </xsl:template>
</xsl:stylesheet>


and create a transformation scenario in Oxygen which applies it over the XML document.

Regards,
Radu

Re: Adding an id-attribute to element

Posted: Wed Jul 12, 2017 2:26 pm
by bee123
Thank you! That works wonderfully!

What would I have to change to put a word in front of the numbers? The first id would look like id=abc01.

Thanks again

Re: Adding an id-attribute to element

Posted: Wed Jul 12, 2017 2:32 pm
by Radu
Hi,

In the XSLT you can compute the @id attribute value like:

Code: Select all

<xsl:attribute name="id" select="concat('abc', count(preceding::text) + 1)"/>


Regards,
Radu