Adding an id-attribute to element

Questions about XML that are not covered by the other forums should go here.
bee123
Posts: 4

Adding an id-attribute to element

Wed Jul 12, 2017 11:53 am

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!
Radu
Posts: 5089

Re: Adding an id-attribute to element

Wed Jul 12, 2017 12:33 pm

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
Radu Coravu
<oXygen/> XML Editor
http://www.oxygenxml.com
bee123
Posts: 4

Re: Adding an id-attribute to element

Wed Jul 12, 2017 2:26 pm

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
Radu
Posts: 5089

Re: Adding an id-attribute to element

Wed Jul 12, 2017 2:32 pm

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
Radu Coravu
<oXygen/> XML Editor
http://www.oxygenxml.com

Return to “General XML Questions”

Who is online

Users browsing this forum: No registered users and 0 guests