2011-03-30 43 views
1

我有兩個XML文件(即有許多共同的節點),看起來有點像這樣:需要從一個文檔複製特定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> 

我要抓住從源節點與「ID」匹配「1003」(在這個例子中),並將其導入到DE STINATION。我正在尋找有關使用importNode(或simpleXML選項)的見解,以及僅獲取我需要的節點的xpath。

+1

XPath表達式將是'/ items/item [id = 1003]'。 – 2011-03-30 21:21:47

回答

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(); 
+0

這是我第一次去的路線,它對我很有用。 xpath的工作原理正確,一切都在發生。巨大的幫助 - 而且很容易理解。謝謝! – ropadope 2011-04-01 15:37:38

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()); 
相關問題