需要将特定XML节点从一个doc复制到另一个doc

时间:2011-03-30 21:07:47

标签: php xml xpath

我有两个XML文件(有许多公共节点)看起来有点像这样:

DESTINATION FILE: ('destination.xml')
<items>
    <item>
         <title>Item A</title>
         <description>This is the description for Item A</description>
         <id>1001</id>
    </item>
    <item>
         <title>Item B</title>
         <description>This is the description for Item B</description>
         <id>1002</id>
    </item>
    <item>
         <title>Item D</title>
         <description>This is the description for Item D</description>
         <id>1004</id>
    </item>

SOURCE FILE: ('source.xml')
<items>
    <item>
         <title>Item A</title>
         <description>This is the description for Item A</description>
         <id>1001</id>
    </item>
    <item>
         <title>Item C</title>
         <description>This is the description for Item C</description>
         <id>1003</id>
    </item>
    <item>
         <title>Item B</title>
         <description>This is the description for Item B</description>
         <id>1002</id>
    </item>

我需要从SOURCE中获取节点,其中'id'匹配'1003'(在本例中)并将其导入DESTINATION。我正在寻找使用importNode(或simpleXML选项)以及xpath的洞察力,只获取我需要的节点。

2 个答案:

答案 0 :(得分:2)

就这样做,它应该有效:

<?php
header('Content-type: application/xml'); //Just to test in the browser directly and have a good format

$docSource = new DOMDocument();
$docSource->loadXML(file_get_contents('source.xml'));
$docDest = new DOMDocument();
$docDest->loadXML(file_get_contents('destination.xml'));

$xpath = new DOMXPath($docSource);

$result = $xpath->query('//item[id=1003]')->item(0); //Get directly the node you want

$result = $docDest->importNode($result, true); //Copy the node to the other document

$items = $docDest->getElementsByTagName('items')->item(0);
$items->appendChild($result); //Add the copied node to the destination document

echo $docDest->saveXML();

答案 1 :(得分:0)

要获得正确的节点,我认为您的XPath应如下所示:

$xpath->query('/items/item/id[.="1003"]/..')

要将其导入其他文档,您需要创建文档并调用importNode并将第二个参数设置为true

$newDom = new DOMDocument;
$newDom->load('destination.xml');

$newNode = $newDom->importNode($el, true);
$newDom->firstChild->appendChild($newNode);

file_put_contents('destination.xml', $newDom->saveXML());