Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I rename an attribute using XSLT?

Tags:

xml

xslt

I have an xml like this:

<person name="foo" gender = "male" />

I want to transform it to

<person id="foo" gender="male" />

Is there a way to do that using XSLT?

  • I will have a lot of child nodes in person

  • I will have more attributes in the person.

like image 418
unj2 Avatar asked Apr 20 '10 23:04

unj2


People also ask

How do I change the value of a variable in XSLT?

You cannot - 'variables' in XSLT are actually more like constants in other languages, they cannot change value.

What is local name () in XSLT?

XSLT/XPath Reference: XSLT elements, EXSLT functions, XPath functions, XPath axes. The local-name function returns a string representing the local name of the first node in a given node-set.

What is text () in XSLT?

XSLT <xsl:text> The <xsl:text> element is used to write literal text to the output. Tip: This element may contain literal text, entity references, and #PCDATA.


1 Answers

This is very simple: Use the identity transform and create a template that transforms the name attribute:

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

<xsl:template match="@name">
   <xsl:attribute name="id">
      <xsl:value-of select="."/>
   </xsl:attribute>
</xsl:template>

This will leave everything in the document except for name attributes exactly as it is. If you only want to change the name attribute on person elements, put a more restrictive XPath in the template's match attribute, e.g. person/@name.

like image 68
Robert Rossney Avatar answered Sep 20 '22 05:09

Robert Rossney