I have these two xml documents:
XML 1:
<outer>
<foo>
<foo-child name="fA" special="true">
content of fA
</foo-child>
<foo-child name="fB">
content of fB
</foo-child>
</foo>
<bar>
<bar-child name="bA">
content of bA
</bar-child>
<bar-child name="bB" special="true">
content of bB
</bar-child>
</foo>
</outer>
XML 2:
<outer>
<foo>
<foo-child name="fA"&g开发者_如何学Ct;
newer and improved content of fA
</foo-child>
<foo-child name="fC">
content of fC
</foo-child>
</foo>
<bar>
<bar-child name="bA" really-special="true" />
<bar-child name="bB" special="false">
Despecialized content of bB
</bar-child>
</foo>
</outer>
I want to merge them together such that elements from document two override elements with the same name
attribute in document one. If no attribute or content is present in the second document is present, it is inherited from the first. So:
Combined
<outer>
<foo>
<foo-child name="fA" special="true">
newer and improved content of fA
</foo-child>
<foo-child name="fB">
content of fB
</foo-child>
<foo-child name="fC">
content of fC
</foo-child>
</foo>
<bar>
<bar-child name="bA" really-special="true">
content of bA
</bar-child>
<bar-child name="bB">
Despecialized content of bB
</bar-child>
</foo>
</outer>
My intent is to do this server-side with PHP.
However, i'm unsure whether this is a job for DomDocument
or SimpleXML. I haven't really used either, and keep thinking "I wish I had jQuery".
Is there a simple solution to this problem?
Going with SimpleXML is the right path there and probably easier one. Here is a good tutorial on how to use it:
Introduction To SimpleXML With PHP
Link is fine now. I agree with Sarfraz, and this is nice solution to merge XMLs with SImpleXML from comment on PHP manual page, working also with attributes too:
function append_simplexml(&$simplexml_to, &$simplexml_from)
{
foreach ($simplexml_from->children() as $simplexml_child)
{
$simplexml_temp = $simplexml_to->addChild($simplexml_child->getName(), (string) $simplexml_child);
foreach ($simplexml_child->attributes() as $attr_key => $attr_value)
{
$simplexml_temp->addAttribute($attr_key, $attr_value);
}
append_simplexml($simplexml_temp, $simplexml_child);
}
}
There also is sample of usage.
精彩评论