Renaming a DOM element with XSL

When playing with the PHP classes for DOM manipulation I found out that there isn't a method to rename an element in the DOM, well, also someone else came across this thing.

I wonder why they don't allow renaming a DOM element, but anyhow you can always use XSL to do this kind of manipulations, let's see how:

<?php

// The document to transform
$xml = <<<'EOM'
<?xml version="1.0"?>
<root>
  <old>
  Text
  </old>
</root>
EOM;

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml);

// The stylesheet which renames the <old></old> element into <new></new>
$stylesheet = <<<'EOM'
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes" />

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

<xsl:template match="old">
  <xsl:element name="new">
    <!-- the select below makes sure the attributes are preserved too -->
    <xsl:apply-templates select="@*|node()" />
  </xsl:element>
</xsl:template>

</xsl:stylesheet>
EOM;

$xsl = new DOMDocument;
$xsl->loadXML($stylesheet);

$xp = new XSLTProcessor();
$xp->importStylesheet($xsl);

// transform the XML using the stylesheet
$output = $xp->transformToXML($xmlDoc);
if (FALSE === $output)
    trigger_error('XSL transformation failed.', E_USER_ERROR);

echo '<pre>' . htmlspecialchars($xml) . '</pre>';
echo '<pre>' . htmlspecialchars($output) . '</pre>';

This and other useful notes about XML and XSL can be found in this old but still good article.


CommentsSyndicate content

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
3
v
d
L
E
6
Enter the code without spaces.