PHP SimpleXML->addChild - unwanted empty namespace attribute

谁都会走 提交于 2019-12-23 17:56:32

问题


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?

:}


回答1:


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.



来源:https://stackoverflow.com/questions/4672274/php-simplexml-addchild-unwanted-empty-namespace-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!