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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里