doxqszx09742 2014-07-24 17:25
浏览 46
已采纳

如何将XML字符串附加到DOMDocument对象?

Creating the DOMDocument object:

$getToken = '<getToken>...</getToken>';
$getToken_objeto = new DOMDocument("1.0", "UTF-8");
$getToken_objeto -> loadXML($getToken);

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);

I get 2 errors:

Fatal error: Uncaught exception 'DOMException' with message 'Wrong Document Error' in C:... DOMException: Wrong Document Error in C:...

Seems simple to resolve but im quite unexperienced using the PHP DOM extension.

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • dongqiang5865 2014-07-24 21:19
    关注

    You're trying to append the original node - not the imported one.

    $Signature_node = $getToken_objeto->importNode(
      $Signature_nodeList->item(0), true
    );
    

    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);
    

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?