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.


![Validate my RSS feed [Valid RSS]](https://ao2.it/sites/default/files/valid-rss-rogers.png)

Comments
Post new comment