2

I am editing an XML file and need to populate it with data from a database. DOM works but it is unable to scale to several hundreds of MBs so I am now using XMLReader and XMLWriter which can write the very large XML file. Now, I need to select a node and add children to it but I can't find a method to do it, can someone help me out?

I can find the node I need to add children to by:

if ($xmlReader->nodeType == XMLReader::ELEMENT && $xmlReader->name == 'data')
    {
        echo 'data was found';
        $data = $xmlReader->getAttribute('data');


    }

How do I now add more nodes/children to the found node? Again for clarification, this code will read and find the node, so that is done. What is required is how to modify the found node specifically? Is there a way with XMLWriter for which I have not found a method that will do that after reading through the class documentation?

4

1 回答 1

1

默认扩展节点(您的问题中缺少)

$node = $xmlReader->expand();

不可使用 XMLReader 进行编辑(通过该名称有意义)。但是,如果将其导入新的,则可以使特定的DOMNode 可编辑DOMDocument

$doc  = new DOMDocument();
$node = $doc->importNode($node);

然后,您可以执行 DOM 提供的任何 DOM 操作,例如添加文本节点:

$textNode = $doc->createTextNode('New Child TextNode added :)');
$node->appendChild($textNode);

如果您更喜欢 SimpleXML 进行操作,您还可以在将节点导入到 SimpleXML后将其导入DOMDocument

$xml = simplexml_import_dom($node);

上面的一个示例使用了我的xmlreader-iterators,它只是为我提供了一些更好的接口XMLReader

$reader  = new XMLReader();
$reader->open($xmlFile);

$elements = new XMLElementIterator($reader, 'data');
foreach ($elements as $element) 
{
    $node = $element->expand();
    $doc  = new DOMDocument();
    $node = $doc->importNode($node, true);
    $node->appendChild($doc->createTextNode('New Child TextNode added :)'));

    echo $doc->saveXML($node), "\n";
}

使用以下 XML 文档:

<xml>
    <data/>
    <boo>
        <blur>
            <data/>
            <data/>
        </blur>
    </boo>
    <data/>
</xml>

上面的小示例代码产生以下输出:

<data>New Child TextNode added :)</data>
<data>New Child TextNode added :)</data>
<data>New Child TextNode added :)</data>
<data>New Child TextNode added :)</data>
于 2013-04-05T22:45:31.143 回答