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.


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

CAPTCHA
Questa domanda serve a verificare che il form non venga inviato da procedure automatizzate
3
P
S
d
c
n
Enter the code without spaces.