drt5813 2017-11-06 15:02
浏览 36
已采纳

按属性合并SimpleXML元素

I have 2 SimpleXMLElements. They both have the same elements (identical ID attributes), but different tags, and I want to merge them together.

Is there any SimpleXML function I can use to do this, or will I have to loop through all the elements to generate a new SimpleXmlElement?

File 1

<Elements>
    <Element ID="352">
        <SomeTag35>Some value</SomeTag35>
        <SomeTag99>Some other value</SomeTag99>
    </Element>
    <Element ID="353">
        <SomeTag35>A value</SomeTag35>
        <SomeTag99>Another value</SomeTag99>
    </Element>
</Elements>

File 2

<Elements>
    <Element ID="352">
        <SomeTag15>Value</SomeTag15>
        <SomeTag44>Value2</SomeTag44>
    </Element>

    <Element ID="353">
        <SomeTag15>Value</SomeTag15>
        <SomeTag44>Value</SomeTag44>
    </Element>
</Elements>

I'm looking to some how end up with

<Elements>
    <Element ID="352">
        <SomeTag35>Some value</SomeTag35>
        <SomeTag99>Some other value</SomeTag99>
        <SomeTag15>Value</SomeTag15>
        <SomeTag44>Value</SomeTag44>
    </Element>
    <Element ID="353">
        <SomeTag35>A value</SomeTag35>
        <SomeTag99>Another value</SomeTag99>
        <SomeTag15>Value</SomeTag15>
        <SomeTag44>Value</SomeTag44>
    </Element>
</Elements>
  • 写回答

1条回答 默认 最新

  • dongrui6787 2017-11-07 07:54
    关注

    SimpleXML is good for doing simple tasks like this. The idea is to read the first document and then use XPath to find the corresponding element in the second document. Then copy the elements from the second document into the first.

    $doc1 = simplexml_load_file('file1.xml');
    $doc2 = simplexml_load_file('file2.xml');
    foreach ( $doc1 as $element )  {
        $extraData = $doc2->xpath("//Element[@ID=\"{$element['ID']}\"]");
        foreach ( $extraData[0]->children() as $newElements ){
            $element->addChild($newElements->getName(), (string)$newElements);
        }
    }
    
    echo $doc1->asXML();
    

    Note that this only works with simple structures. If your document has nested data or attributes, you are better off using DOMDocument where you can copy nodes using importNode which allows you to copy the content with all dub elements as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,