0

I have xml with the following structure:

<?xml version="1.0"?>
<ONIXMessage xmlns="http://test.com/test">
 ...data...
</ONIXMessage>

I need to change xmlns attribute with my own value. How can I do it? Preferably with DOMDocument class.

0

1 Answer 1

2

I need to change xmlns attribute with my own value. How can I do it? Preferably with DOMDocument class.

This by design is not possible. Every DOMDocument has a single root/document element.

In your example XML that root element is:

{http://test.com/test}ONIXMessage

I write the element name as an expanded-name with the convention to put the namespace URI in front enclosed in angle brackets.

Writing the element name in a form that shows it's entire expanded-name also demonstrates that you do not only want to change the value of an attribute here, but you want to change the namespace URI of a specific element. So you want to change the element name. And probably also any child element name it contains if the child is in the same namespace.

As the xmlns attribute only reflects the namespace URI of the element itself, you can not change it. Once it is set in DOMDocument, you can not change it.

You can replace the whole element, but the namespace of the children is not changed either then. Here an example with an XML similar to yours with only textnode children (which aren't namespaced):

$xml = <<<EOD
<?xml version="1.0"?>
<ONIXMessage xmlns="uri:old">
 ...data...
</ONIXMessage>
EOD;

$doc = new DOMDocument();
$doc->loadXML($xml);
$newNode = $doc->createElementNS('uri:new', $doc->documentElement->tagName);
$oldNode = $doc->replaceChild($newNode, $doc->documentElement);

foreach(iterator_to_array($oldNode->childNodes, true) as $child) {
    $doc->documentElement->appendChild($child);
}

Resulting XML output is:

<?xml version="1.0"?>
<ONIXMessage xmlns="uri:new">
 ...data...
</ONIXMessage>

Changing the input XML now to something that contains children like

<?xml version="1.0"?>
<ONIXMessage xmlns="uri:old">
   <data>
     ...data...
   </data>
</ONIXMessage>

Will then create the following output, take note of the old namespace URI that pops up now again:

<?xml version="1.0"?>
<ONIXMessage xmlns="uri:new">
   <default:data xmlns:default="uri:old">
     ...data...
   </default:data>
</ONIXMessage>

As you can see DOMDocument does not provide a functionality to replace namespace URIs for existing elements out of the box. But hopefully with the information provided in this answer so far it is more clear why exactly it is not possible to change that attributes value if it already exists.

The expat based parser in the libxml based PHP extension does allow to "change" existing attribute values regardless if it is an xmlns* attribute or not - because it just parses the data and you can process it on the fly with it.

A working example is:

$xml = <<<EOD
<?xml version="1.0" encoding="utf-8"?>
<ONIXMessage xmlns="uri:old">
  <data>
    ...data...
  </data>
</ONIXMessage>
EOD;

$uriReplace = [
    'uri:old' => 'uri:new',
];

$parser = xml_parser_create('UTF-8');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_set_default_handler($parser, function ($parser, $data) {
    echo $data;
});
xml_set_element_handler($parser, function ($parser, $name, $attribs) use ($xml, $uriReplace) {
    $selfClosing = '/>' === substr($xml, xml_get_current_byte_index($parser), 2);
    echo '<', $name;
    foreach ($attribs as $name => $value) {
        if (substr($name, 0, 5) === 'xmlns' && isset($uriReplace[$value])) {
            $value = $uriReplace[$value];
        }
        printf(' %s="%s"', $name, htmlspecialchars($value, ENT_COMPAT | ENT_XML1));
    }
    echo $selfClosing ? '/>' : '>';
}, function ($parser, $name) use ($xml) {
    $selfClosing = '/>' === substr($xml, xml_get_current_byte_index($parser) - 2, 2);
    if ($selfClosing) return;
    echo '</', $name, '>';
});

xml_parse($parser, $xml, true);
xml_parser_free($parser);

The output then has transparently changed the namespace URI from uri:old to uri:new:

<ONIXMessage xmlns="uri:new">
   <data>
     ...data...
   </data>
</ONIXMessage>

As this example shows, each XML feature you make use of in your XML needs to be handled with the parser. For example the XML declaration is missing. However these can be added by implementing missing handler classbacks (e.g. for CDATA sections) or by outputting missing output (e.g. for the "missing" XML declaration). I hope this is helpful and shows you an alternative way on how to change even these values that are not intended to change.

5
  • how about creating a new document with uri:new and copying the nodes from the old document?
    – michi
    Nov 14, 2015 at 14:19
  • @michi: That should be possible as well. Once the new document element is set, I think when you import nodes, they take the already existing prefix. But I don't have a working example at hand as this should be verified first.
    – hakre
    Nov 16, 2015 at 8:35
  • @michi, I have tried creating a new document with a new root node and the according xmlns, however importing any child node from the old document will result in the same problem, the xlmns of the child nodes will point to the old xmlns.
    – khusseini
    Dec 16, 2015 at 10:25
  • @moz: Don't import. Just create new elements with the local-names from the old document you have. If you import nodes, the namespace is part of the node you import (hence the "import"). Copy iteration could perhaps be streamlined with an iterator like github.com/hakre/Iterator-Garden/blob/development/src/DOM/…
    – hakre
    Dec 16, 2015 at 10:34
  • @hakre, thanks for the tip. I'll have a go at it, though I went for now with a good old preg_replace
    – khusseini
    Dec 16, 2015 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.