如何基於普通匹配節點(密鑰或在此示例中:<id>
)通過使用php合併2個XML記錄?通過匹配節點加入或合併兩個XML文件
1.XML:
<record>
<id>001</id>
<other_nodes>...</other_nodes>
...
</record>
<record>
<id>002</id>
...
</record>
2.XML:
<record>
<id>001</id>
<description>abc</description>
...
</record>
<record>
<id>002</id>
<description>def</description>
...
</record>
Merged.xml:
<record>
<id>001</id>
<other_nodes></other_nodes>
<description>abc</description>
...
</record>
<record>
<id>002</id>
<description>def</description>
...
</record>
旁<id>
,在這兩個XML文件中的所有節點都不同(獨特)。目標是將2.xml的內容添加到1.xml中。 (只需將<description>
節點添加到1.xml中也可以完成這項工作!)
我嘗試了幾個編碼(如嵌套的foreach循環),沒有任何工作。我能做的最好的(我試過多個版本):
(由Merge two xml files based on common attribute啓發):
$file = ...
$targetDom = new DOMDocument();
$targetDom->load($file);
$targetXpath = new DOMXpath($targetDom);
$addDom = new DOMDocument();
$addDom->loadXml($file2);
$addXpath = new DOMXpath($addDom);
// copy elements depending on ProductId
foreach ($targetXpath->evaluate('//record') as $record) {
$productId = $record->id->value;
foreach ($addXpath->evaluate('//record[id=\"'.$productId.'\"]') as $attribute) {
$parent_node = $attribute->evaluate('../codename'); //evaluate or xpath?
//$record->appendChild($targetDom->importNode($parent_node));
$newValue = $attribute->description->value;
//$record->addChild("description", $newValue);
$element = $dom->createElement('codename', $newValue);
$record->appendChild($element);
//$targetDom->documentElement->appendChild(
// $targetDom->importNode($parent_node));
}
}
$xmlsave = $targetDom->saveXml();
相關問題: How to join two XML files with a matching node
a)XML2是否有一個不在XML1中的記錄,並且必須包含在組合的XML3中? – michi
是的,在我的情況下,XML2的所有記錄都不同於XML1('id'除外)。 – Olivier
我的意思是,如果在XML2中有'id's不在XML1 – michi