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.

CommentiCondividi contenuti

Invia nuovo commento

Il contenuto di questo campo è privato e non verrà mostrato pubblicamente. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Indirizzi web o e-mail vengono trasformati in link automaticamente
  • Elementi HTML permessi: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Linee e paragrafi vanno a capo automaticamente.

Ulteriori informazioni sulle opzioni di formattazione

Questa domanda serve a verificare che il form non venga inviato da procedure automatizzate
Enter the code without spaces.