PHP: How to replace existing XML node with XMLWriter

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?


Be default the expanded nodes (missing in your question)

$node = $xmlReader->expand();

are not editable with XMLReader (makes sense by that name). However you can make the specific DOMNode editable if you import it into a new DOMDocument :

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

You can then perform any DOM manipulation the DOM offers, eg for example adding a text-node:

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

If you prefer SimpleXML for manipulation, you can also import the node into SimpleXML after it has been imported into the DOMDocument :

$xml = simplexml_import_dom($node);

An example from above making use of my xmlreader-iterators that just offer me some nicer interface to 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";
}

With the following XML document:

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

The small example code above produces the following output:

<data>New Child TextNode added :)</data>
<data>New Child TextNode added :)</data>
<data>New Child TextNode added :)</data>
<data>New Child TextNode added :)</data>
链接地址: http://www.djcxy.com/p/64750.html

上一篇: Nexpose XML报告2.0版,如何从XML中删除HTML?

下一篇: PHP:如何用XMLWriter替换现有的XML节点