0

我有一个 xml,我将克隆父亲并留在克隆节点下。更多给出这个错误。我想知道如何

致命错误:在第 32 行的 C:\xampp\htdocs\xml2\cloneNew.php 中的非对象上调用成员函数 insertBefore()

$xmla = <<<XML
<?xml version="1.0" ?>
<library>
  <book isbn="1001" pubdate="1943-01-01">
    <title><![CDATA[The Fountainhead]]></title>
    <author>Ayn Rand</author>
    <price>300</price>
  </book>
  <book isbn="1002" pubdate="1954-01-01">
    <title><![CDATA[The Lord of the Rings]]></title>
    <author>J.R.R.Tolkein</author>
    <price>500</price>
  </book>
  <book isbn="1006" pubdate="1982-01-01">
    <title><![CDATA[The Dark - Tower San]]></title>
    <author>Stephen King</author>
    <price>200</price>
  </book>
</library>
XML;

$xmlb = <<<XML
<?xml version="1.0" ?>
<library>
  <book isbn="1004" pubdate="1943-01-01">
    <title><![CDATA[The Fountainhead]]></title>
    <author>Ayn Rand</author>
    <price>300</price>
  </book>
</library>
XML;
$dom_01 = new DOMDocument();
$dom_01->loadXML($xmla);
$library_01 = $dom_01->documentElement;

$dom_02 = new DOMDocument();
$dom_02->loadXML($xmlb);
$library_02 = $dom_02->documentElement;

$xpath = new DOMXPath($dom_02);
$result = $xpath->query('/library/book[translate(@pubdate,"-","")>translate("1980-01-01","-","")]');

$library_02 = $library_02->cloneNode(true);
$newElement = $library_01->appendChild($result->item(0));
$library_01->parentNode->insertBefore($newElement, $result->item(0));

header("Content-type: text/xml");
echo $dom->saveXML();


Result:

$xmla = <<<XML
<?xml version="1.0" ?>
<library>
  <book isbn="1001" pubdate="1943-01-01">
    <title><![CDATA[The Fountainhead]]></title>
    <author>Ayn Rand</author>
    <price>300</price>
  </book>
  <book isbn="1002" pubdate="1954-01-01">
    <title><![CDATA[The Lord of the Rings]]></title>
    <author>J.R.R.Tolkein</author>
    <price>500</price>
  </book>
  <book isbn="1004" pubdate="1943-01-01">
    <title><![CDATA[The Fountainhead]]></title>
    <author>Ayn Rand</author>
    <price>300</price>
  </book>
  <book isbn="1006" pubdate="1982-01-01">
    <title><![CDATA[The Dark - Tower San]]></title>
    <author>Stephen King</author>
    <price>200</price>
  </book>
</library>
XML;
4

1 回答 1

0

您正在尝试获取不parentNode存在documentElement这样的节点。

此外,如果您想将一个文档中的节点放入另一个文档DOMDocument.importNode中,而不是使用 cloneNode。

于 2012-10-25T18:37:33.243 回答