How to set namespace (xmlns) declaration at root t

2019-08-09 01:55发布

问题:

Error "Uncaught exception 'DOMException' with message 'Namespace Error'" in

 $dom = new DOMDocument('1.0', 'utf-8');
 $root = $dom->createElement('MyRoot','Hello');
 $root->setAttributeNS('http://www.w3.org/1999/xlink','xmlns:xlink','xlink');
 $dom->appendChild($root);
 die($dom->saveXML());

How to set an xmlns declaration at root tag? to produce

  <MyRoot xmlns:xlink="http://www.w3.org/1999/xlink"/>Hello</MyRoot>

回答1:

The namespace of the xmlns:xlink is not its value, but a standard namespace. The prefix xmlns is used for the standard namespace http://www.w3.org/2000/xmlns/. You do not need to define that namespace.

All namespace attributes (except for xmlns="...") are part of this namespace.

$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('MyRoot','Hello');
$root->setAttributeNS(
  'http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink'
);
$dom->appendChild($root);

echo($dom->saveXML());

Output:

<?xml version="1.0" encoding="utf-8"?>
<MyRoot xmlns:xlink="http://www.w3.org/1999/xlink">Hello</MyRoot>


回答2:

Set the XMLNS namespace, then the attribute name of xmlns:xlink, and then the value of the attribute you want to set ... which is the xlink url.

$dom = new DOMDocument('1.0', 'utf-8');
$root = $dom->createElement('MyRoot','Hello');
$root->setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:xlink','http://www.w3.org/1999/xlink');
$dom->appendChild($root);
die($dom->saveXML());

<?xml version="1.0" encoding="utf-8"?>
<MyRoot xmlns:xlink="http://www.w3.org/1999/xlink">Hello</MyRoot>