【发布时间】:2014-11-04 09:14:11
【问题描述】:
我正在使用 PHP 为我们的一个客户创建 XML 响应,其中包含名称空间 URL。我期待的输出如下,
<?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;
演示: 演示在这里,http://codepad.org/11W9dLU9
这里的问题是,第三个属性是setAttributeNS PHP 函数的强制属性。所以,我得到的输出是,
<?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?我用谷歌搜索了很多,但找不到任何有用的答案。
对此的任何想法都会很棒。请帮忙。
【问题讨论】:
-
xmlns:* 属性的命名空间不是它的值:stackoverflow.com/a/26594433/2265374
标签: php xml domdocument