0

我有两个 xml 数组,我想将这些数组合并到第三个数组中……第一个 xml 结构是

$current = '<forms id="frm16648">
  <group ref="" id="tarascioheader" mode="block">
    <label>
    <![CDATA[Group (tarascioheader)]]>
    </label> structure u
    <select ref="" id="petorresp">
      <label>
      <![CDATA[Select (petorresp)]]>
      </label>
    </select>

第二个数组是

$old = '<forms id="frm16648">
  <group ref="" id="tarascioheader" mode="block">
    <label>
    <![CDATA[abc]]>
    </label>
 </group>
</forms>':
  </group>
</forms>';

从这些 xmls 中,我想复制新数组中的所有匹配标签......我试图通过一个递归函数来做到这一点......

function merge_xmls($current, $old) 
{

    $cxml = str_get_html($current); 
    $oxml = str_get_html($old); 
    do
    {
        $tt = $cxml->first_child();
        if(!empty($tt) && !is_null($cxml->first_child()))
        {

            $x = $cxml->first_child();

            $this->merge_xmls($x, $cxml, $oxml);
        }
        if(empty($tt))
        {
            $cid = $cxml->id;
            $oid = $oxml -> find('#'.$cid);
            if(!is_null($oid))
            {
                $cxml -> innerHTML = $oxml -> innerHTML;
            }
        }
        $cxml = $cxml->next_sibling();
    }
    while(!empty($cxml) && !is_null($cxml));
}
4

1 回答 1

0

从您发布的伪代码看来,您希望将一个 xml 元素的子元素复制到另一个元素。当我使用不同的解析器时,我对它有点不同,但相同:

  1. 找到要复制到的所有元素。
    1. 根据找到的要复制到的元素来查找要复制的元素。
    2. 删除要复制到的元素的所有子元素。
    3. 将所有子代复制到

我在这里使用 DOMDocument 执行此操作,因为它非常适合诸如此类的专用操作:

$doc = new DOMDocument();

$copyTo = $doc->createDocumentFragment();
$copyTo->appendXML($current);

$copyFrom = new DOMDocument();
$copyFrom->loadXML($old);

$xpath = new DOMXPath($copyFrom);

foreach (new DOMElementFilter($copyTo->childNodes, 'forms') as $form) {
    $id         = $form->getAttribute('id');
    $expression = sprintf('(//*[@id=%s])[1]', xpath_string($id));
    $copy       = $xpath->query($expression)->item(0);

    if (!$copy) {
        throw new UnexpectedValueException("No element with ID to copy from \"$id\"");
    }

    dom_replace_children($copy, $form);
}

输出如下:

echo $doc->saveXML($doc->importNode($copyTo, TRUE));

并给出:

<forms id="frm16648">
  <group ref="" id="tarascioheader" mode="block">
    <label>
    <![CDATA[abc]]>
    </label>
 </group>
</forms>

这里的帮助例程是:

function dom_remove_children(DOMElement $node)
{
    while ($node->firstChild) {
        $node->removeChild($node->firstChild);
    }
}

function dom_replace_children(DOMElement $from, DOMElement $into)
{
    dom_remove_children($into);

    $doc = $into->ownerDocument;

    foreach ($from->childNodes as $child) {
        $into->appendChild($doc->importNode($child, TRUE));
    }
}

还有DOMElementFilter(通过PHP DOM:How to get child elements by tag name in an Elegant way?)还有xpath_string()函数(也如Stackoverflow 所示)。

希望这会有所帮助,该示例以这种方式与您的数据一起使用:https ://eval.in/59886

于 2013-11-02T19:17:51.463 回答