将名称空间添加到XML
问题描述:
我使用PHP为名称空间URL创建了我们的客户之一的XML响应。我期待输出如下,将名称空间添加到XML
<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema">
<Content>
<field1>fieldvalue1</field1>
</Content>
</ns3:userResponse>
但是,通过使用下面的代码,
<?php
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');
// create root node
$root = $doc->createElementNS('http://www.w3.org/2001/XMLSchema-instance', 'ns3:userResponse');
$root = $doc->appendChild($root);
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');
// add node for each row
$occ = $doc->createElement('Content');
$occ = $root->appendChild($occ);
$child = $doc->createElement("field1");
$child = $occ->appendChild($child);
$value = $doc->createTextNode('fieldvalue1');
$value = $child->appendChild($value);
// get completed xml document
$xml_string = $doc->saveXML();
echo $xml_string;
DEMO: 演示是在这里,http://codepad.org/11W9dLU9
这里的问题是,第三个属性是PHP函数setAttributeNS的强制属性。所以,我得到的输出,
<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema" ns3:schemaLocation="" ns2:schemaLocation="">
<Content>
<field1>fieldvalue1</field1>
</Content>
</ns3:userResponse>
所以,反正是有删除ns3:schemaLocation
和ns2:schemaLocation
这与空值来吗?我GOOGLE了很多,但无法找到任何有用的答案。
对此的任何想法都会很棒。请帮忙。
答
你创建这个属性:
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');
删除此行,他们将被删除。
如果你想添加一些的xmlns没有在代码中使用,它是:
$attr_ns = $doc->createAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:attr');
阅读本评论:http://php.net/manual/pl/domdocument.createattributens.php#98210
在根标签[如何设置命名空间(的xmlns)声明的
可能重复,与“纯DOM”?](http://stackoverflow.com/questions/26594261/how-to-set-namespace-xmlns-declaration-at-root-tag-with-pure-dom) – ThW 2014-11-04 12:05:00
xmlns的命名空间: *属性不是它的值:http://stackoverflow.com/a/26594433/2265374 – ThW 2014-11-04 12:06:53