首页 > 解决方案 > 将小 XML 文件添加到大 XML 文件 PHP 中的特定位置

问题描述

我有一个像这样的大 XML 文件

<?xml version="1.0" encoding="utf-8"?>
<catpharma date_generation="28-02-2019" version_xsd="6">
    <cat>
        <node1>xxx</node1>
        <node2>xxx</node2>
        <node3>xxx</node3>
        <date/>
        <!-- data from the small xml files need to be appended here --> 

        <node4>
        ...

然后我有几个小的 XML 文件需要在date节点之后附加。

小的 XML 文件如下所示:

<gamme>
    <id>1234</id>
    <nom>xxx</nom>
    <position>29</position>
    <gamme>
        <id>4567</id>
        <nom>zzz</nom>
        <position>2705</position>
    </gamme>
</gamme>

通过一个循环,我会知道需要附加哪个正确的“小”XML 文件,即每次循环迭代时,都会将一个“小”XML 文件附加到大文件。

最终结果需要如下

<?xml version="1.0" encoding="utf-8"?>
    <catpharma date_generation="28-02-2019" version_xsd="6">
        <cat>
            <node1>xxx</node1>
            <node2>xxx</node2>
            <node3>xxx</node3>
            <date/>
            <gamme>
                <id>1234</id>
                <nom>xxx</nom>
                <position>29</position>
                <gamme>
                    <id>4567</id>
                    <nom>zzz</nom>
                    <position>2705</position>
                </gamme>
            </gamme>
            <!-- more `gamme` nodes from other small XML files to be added here-->
            <node4>
            ...

到目前为止我看到的所有解决方案都建议您在大 XML 文件中创建一个节点,然后继续一一添加子节点的详细信息(例如这个解决方案)。

但问题是因为我已经在小 xml 文件中拥有“游戏”节点,我不能将文件作为一个整体读取并添加到那里吗?(不必逐个读取小 xml 文件中的行一)。

到目前为止,我还没有看到任何我想要实现它的方式的解决方案。

标签: phpxml

解决方案


您无需在目标文档中创建节点。任何有效的 XML 文档都有一个文档元素节点。所以你必须加载主文档,找到特定的节点。迭代详细文档并导入并附加其文档元素。

对于以下示例,我将 XML 剥离并将其放入字符串文字中。使用文件只需更改加载方法。

$mainXML = <<<'XML'
<catpharma>
    <cat>
        <node1/>
        <date/>
        <node4/>
    </cat>    
    <date/>
</catpharma>
XML;

$detailXMLs = [
  '<gamme><id>1234</id></gamme>',
  '<gamme><id>5678</id></gamme>',
];

// create document and load the main XML
$main = new DOMDocument();
$main->preserveWhiteSpace = FALSE;
$main->loadXML($mainXML);
$xpath = new DOMXpath($main);

// iterate the first "date" element in the document
foreach ($xpath->evaluate('(//date)[1]') as $dateNode) {
    // iterate the detail XML strings
    foreach ($detailXMLs as $detailXML) {
        // load into a document
        $detail = new DOMDocument();
        $detail->loadXML($detailXML);

        // append into the parent of the "date" node
        $dateNode->parentNode->insertBefore(
            // import the document elment into the main document
            $main->importNode($detail->documentElement, TRUE),
            // insert before the node following the "date" node
            $dateNode->nextSibling
        );
    }
}

$main->formatOutput = TRUE;
echo $main->saveXML();

输出:

<?xml version="1.0" encoding="UTF-8"?>
<catpharma>
  <cat>
    <node1 />
    <date />
    <gamme>
      <id>5678</id>
    </gamme>
    <gamme>
      <id>1234</id>
    </gamme>
    <node4 />
  </cat>
  <date />
</catpharma>

推荐阅读