2017-06-27 51 views
3

我一直在努力工作几个小时,试图让输出XML匹配我给出的规范,而我找不到合适的代码来完成它。我使用DOMDocument是因为我读到它比SimpleXML更灵活。带命名空间的DOMDocument

所需的最终结果:

<?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。

+0

确定。 PHP不是我的语言,但我建议你简化。从根元素开始。你把它放到http://www.w3.org/2001/XMLSchema-instance命名空间中,但这不是你想要的。根据你想要的结果,“retail”元素应该没有名字空间。所以$ root = $ node-> createElement('retail');应该做。然后看看如何添加xmlns:i属性,依此类推。一次解决一个问题。 – Alohci

回答

1

除了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

+0

不知道XMLWriter,能够在15分钟内完成DOM中几小时无法完成的任务。我仍然无法围绕命名空间 - 我理解他们的目的,但是在(例如)setAttributeNS中操纵他们让我完全困惑。感谢大家的帮助! –

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