你可能需要編寫自己的導入代碼,然後。例如。
function importNS(DOMNode $target, DOMNode $source, $fnImportElement, $fnImportAttribute) {
switch($source->nodeType) {
case XML_ELEMENT_NODE:
// invoke the callback that creates the new DOMElement node
$newNode = $fnImportElement($target->ownerDocument, $source);
if (!is_null($newNode) && !is_null($source->attributes)) {
foreach($source->attributes as $attr) {
importNS($newNode, $attr, $fnImportElement, $fnImportAttribute);
}
}
break;
case XML_ATTRIBUTE_NODE:
// invoke the callback that creates the new DOMAttribute node
$newNode = $fnImportAttribute($target->ownerDocument, $source);
break;
default:
// flat copy
$newNode = $target->ownerDocument->importNode($source);
}
if (!is_null($newNode)) {
// import all child nodes
if (!is_null($source->childNodes)) {
foreach($source->childNodes as $c) {
importNS($newNode, $c, $fnImportElement, $fnImportAttribute);
}
}
$target->appendChild($newNode);
}
}
$target = new DOMDocument;
$target->loadxml('<foo xmlns:myprefix="myprefixUri"></foo>');
$source = new DOMDocument;
$source->loadxml('<a>
<b x="123">...</b>
</a>');
$fnImportElement = function(DOMDocument $newOwnerDoc, DOMElement $e) {
return $newOwnerDoc->createElement('myprefix:'.$e->localName);
};
$fnImportAttribute = function(DOMDocument $newOwnerDoc, DOMAttr $a) {
// could use namespace here, too....
return $newOwnerDoc->createAttribute($a->name);
};
importNS($target->documentElement, $source->documentElement, $fnImportElement, $fnImportAttribute);
echo $target->savexml();
打印
<?xml version="1.0"?>
<foo xmlns:myprefix="myprefixUri"><myprefix:a>
<myprefix:b x="123">...</myprefix:b>
</myprefix:a></foo>
經進一步調查事實證明,我實際上並不需要爲我工作的項目做到這一點。每當我改變命名空間時,只需使用適當的xmlns指標就足夠了。因此我不再需要這個答案;其他人可能會喜歡一個。 – thomasrutter 2010-04-08 13:02:37