问题描述
创建DOMDocument对象:
Creating the DOMDocument object:
$getToken = '<getToken>...</getToken>';
$getToken_objeto = new DOMDocument("1.0", "UTF-8");
$getToken_objeto -> loadXML($getToken);
尝试将XML字符串(签名)附加到上面创建的DOMDocument中:
Trying to append a XML string (Signature) into the DOMDocument created above:
$Signature = '<Signature>...</Signature>';
$Signature_objeto = new DOMDocument("1.0", "UTF-8");
$Signature_objeto -> loadXML($Signature);
$Signature_nodeList = $Signature_objeto -> getElementsByTagName("Signature");
$Signature_node = $Signature_nodeList -> item(0);
$getToken_objeto -> importNode($Signature_node, true);
$getToken_objeto -> appendChild($Signature_node);
我遇到2个错误:
致命错误:C中出现未捕获的异常 DOMException,消息为错误的文档错误:...
DOMException:C中出现了错误的文档错误:...
Fatal error: Uncaught exception 'DOMException' with message 'Wrong Document Error' in C:...DOMException: Wrong Document Error in C:...
似乎很容易解决,但是使用PHP DOM扩展却没有经验。
Seems simple to resolve but im quite unexperienced using the PHP DOM extension.
预先感谢。
推荐答案
您正在尝试附加原始节点-而不是导入的节点。
You're trying to append the original node - not the imported one.
$Signature_node = $getToken_objeto->importNode(
$Signature_nodeList->item(0), true
);
您试图将节点附加到文档中,但是XML文档只能有一个文档元素,并且已经有一个。您可以将其附加到文档元素:
You're trying to append the node to the document, but an XML document can only have a single document element and it already has one. You can append it to the document element:
$getToken_objeto->documentElement->appendChild($Signature_node);
但是PHP可以将XML片段直接加载到DOMDocumentFragment中。
But PHP can load XML fragments directly into a DOMDocumentFragment.
$xml = '<getToken>...</getToken>';
$fragmentXml = '<Signature>...</Signature>';
$dom = new DOMDocument();
$dom->loadXML($xml);
$xpath = new DOMXpath($dom);
$fragment = $dom->createDocumentFragment();
$fragment->appendXml($fragmentXml);
$xpath
->evaluate('//getToken')
->item(0)
->appendChild($fragment);
echo $dom->saveXml();
这篇关于如何将XML字符串附加到DOMDocument对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!