douzai1074 2017-11-23 08:48
浏览 22
已采纳

使用insertBefore并处理同名XML PHP的几个节点

I have an XML which is a catalog containing several range nodes which in turn contain several item nodes:

<cat>
    <range>
        <item>
            <a></a>
            <b></b>
            <c></c>
        </item>
        <item>
            <a></a>
            <b></b>
            <c></c>
        </item>
        <item>
            <a></a>
            <b></b>
            <c></c>
        </item> 
        <item>
            <a></a>
            <b></b>
            <c></c>
        </item>
        <!-- node 'a' need to be added here -->
        <b></b>
        <d></d>
    </range>
    <range>
        <item>
            <a></a>
            <b></b>
            <c></c>
        </item>
        <item>
            <a></a>
            <b></b>
            <c></c>
        </item>
        <!-- node 'a' need to be added here -->
        <b></b>
        <d></d>
    </range>    
</cat>

Now I need to add node a inside each range just after ALL item nodes and just before node b.

NOTE: nodes a & b inside and outside item is the same

I was able to add the b node inside range, like this:

foreach($dom->getElementsByTagname('range') as $range) {
    forearch ($range->getElementsByTagName('d') as $d) {
        $b = $dom->createElement('b');
        $d = $d->parentNode->insertBefore($b, $d);
    }
}

If I use the same code to try and add node a outside all the item nodes, it won't work since the reference node b is the same inside and outside the item nodes; so it will just add node a inside the item nodes.

I found an insertAfter function;

function insertAfter(\DOMNode $newNode, \DOMNode $referenceNode)
{
  if($referenceNode->nextSibling === null) {
      return $referenceNode->parentNode->appendChild($newNode);
  } else {
      return $referenceNode->parentNode->insertBefore($newNode, $referenceNode->nextSibling);
  }
}

but it will not give me the desired result since if I used item as the reference node, it will add the new node just after the first item whereas I need it after all the item nodes.

  • 写回答

2条回答 默认 最新

  • douyue8364 2017-11-23 09:11
    关注

    The easiest way to achieve what you are trying to do is by using xPath.

    $xpath = new DOMXpath($dom);
    $bs = $xpath->query("//range/b");
    $a = new DOMElement('a');
    
    foreach ($bs as $b) {
        $b->parentNode->insertBefore($a, $b);
    }
    

    This gets alls the "b" that are a direct child of range but not its grandchildren.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探