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:


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

$xmlDoc = new DOMDocument();

// The stylesheet which renames the <old></old> element into <new></new>
$stylesheet = <<<'EOM'
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="" version="1.0">
<xsl:output method="xml" indent="yes" />

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

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


$xsl = new DOMDocument;

$xp = new XSLTProcessor();

// 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

This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the code without spaces.