Page 1 of 1

conditionally rename tags upon data/content

Posted: Sat Feb 02, 2008 1:11 am
by rabo
hi,
i cannot figure out how write a XSLT to rename only specific tags and output as XML.

i received xml with "duplicate" xml-tags.
meaning: sometimes the xml-tag <field> should be <field1> and sometime <field2>.
this depends on the xml-tag <field_type> which is put just before <field>.

<field_type>A</fiel_type>
<field>textisenteredhere</field>
<field_type>B</field_type>
<field)textiseneterdherealso, but should have been labeled different</field>


So, if the content of <field_type> = "A" the following <field> should be renamed <field1>. if the content of <field_type> = "B" the following <field> should be renamed <field2>.
The XMl my client has gvenme contains close to 6000 lines, so i would prefer a XSLT to transform this and copy nodes with renamed tags.

thanks for any help

Re: conditionally rename tags upon data/content

Posted: Sat Feb 02, 2008 10:22 am
by george
Hi,

Start with a recursive copy template and then add a match for each case that you want to catch and output field1, field2, etc.

Code: Select all


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.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="field[preceding-sibling::*[1][self::field_type and .='A']]">
<field1>
<xsl:apply-templates select="node() | @*"/>
</field1>
</xsl:template>
<xsl:template match="field[preceding-sibling::*[1][self::field_type and .='B']]">
<field2>
<xsl:apply-templates select="node() | @*"/>
</field2>
</xsl:template>
</xsl:stylesheet>
Best Regards,
George

Re: conditionally rename tags upon data/content

Posted: Sat Feb 02, 2008 6:14 pm
by rabo
George,

thanks very much.
it worked perfectly.