且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将节点从数组添加到多级 XML?

更新时间:2021-08-08 07:07:35

为了坚持使用 DOMDocument,我添加了一个额外的循环以允许您添加所有原始数组项.主要是在添加一个新项目进来,检查它是否已经存在...

To stick with using DOMDocument, I've added an extra loop to allow you to add all of the original array items in. The main thing is before adding a new item in, check if it's already there...

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

$set=array("A-B-C-D","A-B-E","A-B-C-F-G", "A-B-G-Q");
$doc = new DomDocument();

$doc->formatOutput=true;
$doc->LoadXML('<root/>');
foreach ( $set as $input ) {
    $arr=explode("-",$input);    
    $base = $doc->documentElement;
    foreach($arr as $a2) {
        $newcomm = null;
        // Decide if the element already exists.
        foreach ( $base->childNodes as $nextElement )   {
            if ( $nextElement instanceof DOMElement 
                    && $nextElement->tagName == $a2 )   {
                $newcomm = $nextElement;
            }
        }
        if ( $newcomm == null )   {
            $newcomm = $doc->createElement($a2);
            $base->appendChild($newcomm);
        }
        $base=$newcomm;
    } 
}
echo $doc->saveXML();

由于没有快速的方法(据我所知)来检查具有特定标签名称的子元素,它只是在所有子元素中查找具有相同名称的 DOMElement.

As there is no quick way ( as far as I know) to check for a child with a specific tag name, it just looks through all of the child elements for a DOMElement with the same name.

我开始使用 getElementByTagName,但这会找到具有该名称的任何子节点,而不仅仅是在当前级别.

I started using getElementByTagName, but this finds any child node with the name and not just at the current level.

上面的输出是...

<?xml version="1.0"?>
<root>
  <A>
    <B>
      <C>
        <D/>
        <F>
          <G/>
        </F>
      </C>
      <E/>
      <G>
        <Q/>
      </G>
    </B>
  </A>
</root>

我添加了一些其他项目以表明它在正确的位置添加了东西.

I added a few other items in to show that it adds things in at the right place.