如果你不希望有一个虚拟的属性添加到您的根元素,你可以手动上通过添加xmlns
属性为您i
前缀声明命名空间:
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
为了做到这一点,正如现有的答案(Unable to add Attribute with Namespace Prefix using PHP Simplexml)所暗示的那样,您必须在xmlns:
前添加新属性的前缀(因为xmlns:
命名空间基本没有在您的文档中声明)。而且,由于xmlns:
是该属性的名称的一部分,你therfore需要的xmlns:
$uri = 'http://www.w3.org/2001/XMLSchema-instance';
$root = new SimpleXMLElement('<root/>');
$root->addAttribute('xmlns:xmlns:i', $uri);
######
$child = $root->addChild('foo');
$child->addAttribute('xmlns:i:bar', 'baz');
######
echo $root->asXml();
出现两次,得到(手动格式化的可读性):
<?xml version="1.0"?>
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<foo i:bar="baz"/>
</root>
所以这xmlns:
前缀似乎欺骗了。请注意,如果你重新加载元素后设置该属性,可以增加孩子时要使用的命名空间URI为好,这不指定前缀:
$root = new SimpleXMLElement($root->asXML());
$child = $root->addChild('foo');
$child->addAttribute('i:bar', 'bazy', $uri);
####
echo $root->asXml();
给出(再次,手动格式化):
<?xml version="1.0"?>
<root xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<foo i:bar="baz"/>
<foo i:bar="bazy"/>
</root>
这第二个例子似乎更接近预期的(或至少是预期的)使用。
请注意,正确执行此操作的唯一方法是使用更完整(但不幸也是更复杂和更详细)DOMDocument类。这在How to declare an XML namespace prefix with DOM/PHP?中概述。
这似乎是一种浪费。它是在每一行上声明命名空间,而不是仅在根上。 –
我认为他正在向根添加一个虚拟属性,只是为了说服SimpleXMLElement添加名称空间声明。丑陋(但PHP的错,而不是VolkerK的),但它的作品,如果你不介意额外的属性。 –
最好的解决方案实际上是由Olivier“Ölbaum” Scherler – 2013-05-15 08:29:34