Question

I'm attempting to use SimpleXML's addChild method of the SimpleXMLElement (actually a SimpleXMLIterator which is a subclass of SimpleXMLElement) to add child elements.

My problem is that the source document contains a mixture of elements with namespaces and without. Here's a simple (no pun intended) example:

<?xml version="1.0" encoding="UTF-8"?>
  <ns1:a xmlns:ns1="http://www.abc.com">
</ns1:a>

The PHP code is:

$it = new SimpleXMLIterator ('./test.xml', 0, true);
$it->addChild('d', 'another!'); // adds new child element to parent's NS
$it->addChild('c', 'no namespace for me!', ''); // puts xmlns="" every time :(

//output xml in response:
header('Content-Type: text/xml');

echo $it->saveXML();

The problem - as the comment states - is that if I want to place a child element with no namespace inside of the parent element with a namespace, I get an empty XML namespace attribute every time (output of above PHP code):

<?xml version="1.0" encoding="UTF-8"?>
  <ns1:a xmlns:ns1="http://www.abc.com">
  <ns1:d>another!</ns1:d>
  <c xmlns="">no namespace for me!</c>
</ns1:a>

While both web browsers as well as XML parsers (e.g. Xerces) don't seem to mind this superfluous markup, I find it slightly annoying that I can't seem to tell it to stop doing this.

Anyone have a solution or am I over reacting?

:}

Was it helpful?

Solution

For SimpleXML c needs a namespace. If you specify one, it gets an xmlns attribute because what you specified has not been declared before. If you don't specify a namespace for c, it inherits the namespace from the parent node. The only option here is ns1. (This happens to d.)

To prevent inhertance of the parent namespace and omit empty xmlns you'd need an namespace like xmlns="http://example.com" at the parent. Then $it->addChild('c', 'no ns', 'http://example.com') gives you <c>no ns</c>.

However you cannot inject additional namespaces e.g. with addAttribute. You have to manipulate the input file before it's parsed by SimpleXML. To me this seems even more ugly than removing all empty xmlns attributes from the output.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top