我已经工作了几个小时,试图让输出 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。
最佳答案
除了 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();
此外,请随意测试其他 php XML 内置 api:XMLWriter
关于php - 带命名空间的 DOMDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44785898/