如何使用DOM / PHP声明XML命名空间前缀? [英] How to declare an XML namespace prefix with DOM/PHP?
问题描述
<?xml version = 1.0\" >?;
< root xmlns:p =myNS>
< p:x> test< / p:x>
< / root>
这就是我在做的:
$ xml = new DOMDocument('1.0');
$ root = $ xml-> createElementNS('myNS','root');
$ xml-> appendChild($ root);
$ x = $ xml-> createElementNS('myNS','x','test');
$ root-> appendChild($ x);
echo $ xml-> saveXML();
这是我得到的:
<?xml version =1.0?>
< root xmlns =myNS>
< x> test< / x>
< / root>
我做错了什么?如何使这个前缀工作?
$ root = $ xml-> createElementNS ('myNS','root');
根
不应在命名空间 myns名字
。在原始示例中,它不在命名空间中。
$ x = $ xml-> createElementNS('myNS',' x','test');
替换为$ code> p:x 只是 x
来建议您要使用 p
作为此命名空间的前缀的序列化算法。但是请注意,对于具有命名空间的XML读取器,无论是否使用 p:
,没有语义上的区别。
这将导致 xmlns:p
声明在< p:x>
元素上输出(第一个需要它)。如果您希望声明在根元素上(而且与XML-with-Namespaces读者没有任何区别),那么您必须明确地将 setAttributeNS
。例如:
$ root = $ xml-> createElementNS(null,'root');
$ xml-> appendChild($ root);
$ x = $ xml-> createElementNS('myNS','p:x','test');
$ root-> setAttributeNS('http://www.w3.org/2000/xmlns/','xmlns:p','myNS');
$ root-> appendChild($ x);
I'm trying to produce the following XML by means of DOM/PHP5:
<?xml version="1.0"?>
<root xmlns:p="myNS">
<p:x>test</p:x>
</root>
This is what I'm doing:
$xml = new DOMDocument('1.0');
$root = $xml->createElementNS('myNS', 'root');
$xml->appendChild($root);
$x = $xml->createElementNS('myNS', 'x', 'test');
$root->appendChild($x);
echo $xml->saveXML();
This is what I'm getting:
<?xml version="1.0"?>
<root xmlns="myNS">
<x>test</x>
</root>
What am I doing wrong? How to make this prefix working?
$root = $xml->createElementNS('myNS', 'root');
root
shouldn't be in namespace myNS
. In the original example, it is in no namespace.
$x = $xml->createElementNS('myNS', 'x', 'test');
Set a qualifiedName of p:x
instead of just x
to suggest to the serialisation algorithm that you want to use p
as the prefix for this namespace. However note that to an XML-with-Namespaces-aware reader there is no semantic difference whether p:
is used or not.
This will cause the xmlns:p
declaration to be output on the <p:x>
element (the first one that needs it). If you want the declaration to be on the root element instead (again, there is no difference to an XML-with-Namespaces reader), you will have to setAttributeNS
it explicitly. eg.:
$root = $xml->createElementNS(null, 'root');
$xml->appendChild($root);
$x = $xml->createElementNS('myNS', 'p:x', 'test');
$root->setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:p', 'myNS');
$root->appendChild($x);
这篇关于如何使用DOM / PHP声明XML命名空间前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!