我现在非常沮丧,因为我似乎不明白为什么将一个节点(包含所有孩子)从一个XML树复制到另一个XML树很困难。
我googled很多,似乎我必须使用SimpleXML读取树,然后将节点解析为DOM以某种方式导入/导出它们。 是否应该有一个功能一次性这样做?
基本上我想从源所有processList->处理条目复制到目标test-> processList->
source:
<processList>
<process ...>
//some more child nodes
</process>
</processList>
destination:
<test>
<processList>
<process ...>
//some more child nodes
</process>
</processList>
</test>
有人可以提出建议吗?
答案 0 :(得分:2)
DOM可以轻松完成此任务。 DOMDocument::importNode()
允许从其他文档导入节点。可以像任何节点一样附加/插入导入的节点。
DOMXpath::evaluate()
可用于从DOM中获取节点。
$sourceXml = <<<'XML'
<processList>
<process from="source">
//some more child nodes
</process>
</processList>
XML;
$targetXml = <<<'XML'
<test>
<processList>
<process from="target">
//some more child nodes
</process>
</processList>
</test>
XML;
$source = new DOMDocument();
$source->loadXml($sourceXml);
$sourceXpath = new DOMXPath($source);
$target = new DOMDocument();
$target->preserveWhiteSpace = false;
$target->formatOutput = true;
$target->loadXml($targetXml);
$targetXpath = new DOMXPath($target);
$targetNode = $targetXpath->evaluate('//processList[1]')->item(0);
foreach ($sourceXpath->evaluate('//process') as $process) {
$targetNode->appendChild(
// import the node into the target document
$target->importNode($process, TRUE)
);
}
echo $target->saveXml();
输出:
<?xml version="1.0"?>
<test>
<processList>
<process from="target">
//some more child nodes
</process>
<process from="source">
//some more child nodes
</process>
</processList>
</test>