带命名空间的DOMDocument

时间:2017-06-27 16:56:43

标签: php xml dom simplexml domdocument

我已经工作了几个小时试图让输出XML与我给出的规范相匹配,而我却找不到合适的代码来完成它。我正在使用DOMDocument,因为我读到它比SimpleXML更灵活。

期望的最终结果:

<?xml version="1.0" encoding="UTF-8"?>
<retail xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
    <partnerid>XYZ</partnerid>
    <customer xmlns:a="http://schemas.datacontract.org/2004/07/DealerTrack.DataContracts.CreditApp">
        <a:info>
            <a:FirstName>Bob</a:FirstName>
            <a:LastName>Hoskins</a:LastName>
        </a:info>
    </customer>
    <refnum i:nil="true"/>
</retail>

...以及我用来实现的代码(缩写):

$node = new DOMDocument('1.0', 'UTF-8');
$root = $node->createElementNS( 'http://www.w3.org/2001/XMLSchema-instance', 'retail' );
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:i', 'test');

$capp = $node->appendChild($root);

$cnode = $node->createElement("partnerid", 'XYZ');
$capp->appendChild($cnode);

......这不是我想要的东西。我已经尝试了至少十几个createElementNS,setAttributeNS的组合,查看了几个例子,找不到任何让我接近我所追求的东西。我已经可以在SimpleXML中执行此操作,但我想了解正在发生的事情以及如何在此实例中使用DOM。

2 个答案:

答案 0 :(得分:2)

除了alex blex回答:对于根元素(仅适用于它),您还可以简单地创建一个属性命名空间,而不将其附加到根元素。

$dom = new DOMDocument('1.0', 'UTF-8');

$namespaceURIs = [
  'xmlns' => 'http://www.w3.org/2000/xmlns/',
  'i' => 'http://www.w3.org/2001/XMLSchema-instance',
  'a' => 'http://schemas.datacontract.org/2004/07/DealerTrack.DataContracts.CreditApp'
];

$root = $dom->createElement('retail');
$dom->appendChild($root);
$dom->createAttributeNS($namespaceURIs['i'], 'i:attr');
// note that you don't have to append it: `CreateAttributeNS` defines a namespace for
// the entire document and will be automatically attached to the root element.

$root->appendChild($dom->createElement('partnerid', 'XYZ'));

$customer = $dom->createElement('customer');
$customer->setAttributeNS($namespaceURIs['xmlns'], 'xmlns:a', $namespaceURIs['a']);
// `setAttributeNS` allows to define local namespaces, that's why it needs to be
// attached to a particular element.
$root->appendChild($customer);

$info = $dom->createElementNS($namespaceURIs['a'], 'a:info');
$customer->appendChild($info);
// etc.

$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;

echo $dom->saveXML();

demo

另外,随意测试其他php XML内置API:XMLWriter

答案 1 :(得分:1)

如果我理解问题是retail元素。

$node = new DOMDocument('1.0', 'UTF-8');
$root = $node->createElement('retail' );
$root->setAttributeNS(
    'http://www.w3.org/2000/xmlns/',
    'xmlns:i',
    'http://www.w3.org/2001/XMLSchema-instance'
);

$capp = $node->appendChild($root);

$cnode = $node->createElement("partnerid", 'XYZ');
$capp->appendChild($cnode);

应该给你预期的输出。 http://php.net/manual/en/domdocument.createelementns.php

中有详细记录