如何将节点从数组添加到多级 XML?
我有一个数组 $arr=array("A-B-C-D","A-B-E","A-B-C-F")
我预期的 XML 输出应该是
I have an array $arr=array("A-B-C-D","A-B-E","A-B-C-F")
and my expected output of the XML should be
<root>
<A>
<B>
<C>
<D></D>
<F></F>
</C>
<E></E>
</B>
</A>
</root>
我已经完成了为第一个数组元素(即 A-B-C-D)创建 XML 新节点的代码.但是当我移动到第二个元素时,我需要检查已经创建了多少个节点 (A-B),然后根据它在适当的位置添加新节点.
I have already done the code that creates a new node of the XML for the first array element i.e. A-B-C-D. But when I move to the second element I need to check how many nodes are already created (A-B) and then add the new node based on that in the proper position.
那么我如何遍历 XML 并找到应该附加新节点的确切位置?
So how do I traverse the XML and find the exact position where the new node should be attached?
我当前的代码是这样的
$arr=explode("-",$input);
$doc = new DomDocument();
$doc->formatOutput=true;
$doc->LoadXML('<root/>');
$root = $doc->documentElement;
$comm = $doc->createElement('comm');
$root->appendChild($comm);
foreach($arr as $a2) {
$newcomm = $doc->createElement($a2);
$community->appendChild($newcomm);
$community=$newcomm;
}
我应该使用 xpath 还是其他一些更容易的方法?
Should I use xpath or some other method will be easier?
为了坚持使用 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.