PHP SimpleXML-> addChild-不需要的空名称空间属性 [英] PHP SimpleXML->addChild - unwanted empty namespace attribute
问题描述
我正在尝试使用SimpleXMLElement的SimpleXML的addChild方法(实际上是SimpleXMLElement的子类SimpleXMLIterator)来添加子元素.
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>
PHP代码为:
$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();
问题-正如评论所指出的-如果我想将没有命名空间的子元素放置在带有命名空间的父元素内,则每次都会得到一个空的XML命名空间属性(上述PHP代码的输出):
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>
虽然Web浏览器和XML解析器(例如Xerces)似乎都不介意这种多余的标记,但我似乎有点讨厌,因为我似乎无法告诉它停止这样做.
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?
:}
推荐答案
对于SimpleXML,c需要一个名称空间.如果您指定一个,它将获得xmlns属性,因为您之前未声明过指定的内容.如果未为c指定名称空间,则它将从父节点继承名称空间.这里唯一的选择是ns1
. (这恰好是d.)
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.)
为防止父名称空间的继承,并且省略空的xmlns
,您需要在父名称空间使用xmlns="http://example.com"
之类的名称空间.然后$it->addChild('c', 'no ns', 'http://example.com')
给您<c>no ns</c>
.
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>
.
但是,您不能注入其他名称空间,例如使用addAttribute
.您必须先处理输入文件,然后再用SimpleXML对其进行解析.对我来说,这似乎比从输出中删除所有空的xmlns属性还要难看.
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.
这篇关于PHP SimpleXML-> addChild-不需要的空名称空间属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!