编辑XML文件(删除节点并添加新节点)

I have problems to deal with XML in PHP. What i want is to remove a not needed element and replace it with a other one.

Let's say the XML looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<software>
    <info>
        <version>1.2</version>
        <lasterror>1386680712</lasterror>
    </info>
    <decryption>
        <funcgroup siglength="86">
            <func>
                <name>Mk</name>
                <args>$a</args>
                <code>XXXX</code>
            </func>
            <func>
                <name>Nk</name>
                <args>$a,$b</args>
                <code>XXXX</code>
            </func>
        </funcgroup>
    </decryption>
</software>

PHP Code:

$domtree = new DOMDocument('1.0', 'UTF-8');
$domtree->loadXML(file_get_contents('test.xml'));

$thedocument = $domtree->documentElement;

$list = $thedocument->getElementsByTagName('funcgroup');
foreach ($list as $domElement) {
    $sig_length = $domElement->getAttribute('siglength');
    if($sig_length == $signature_length) {
        $domElement->parentNode->removeChild($domElement);
        break;
    }
}

$some_stuff = $domtree->getElementsByTagName('software');
$some_stuff = $domtree->getElementsByTagName('decryption');
$funcgroup = $domtree->appendChild($domtree->createElement('funcgroup'));
$funcgroup->setAttribute('siglength', $signature_length);

$func = $funcgroup->appendChild($domtree->createElement('func'));
$func->appendChild($domtree->createElement('name', $outer_element[0]));
$func->appendChild($domtree->createElement('args', $outer_element[1]));
$code = $func->appendChild($domtree->createElement('code'));
$code->appendChild($domtree->createTextNode($outer_element[2]));

Note: I removed some stuff otherwise it would get too complicated i guess. The above code shows what i do, but without some other loops and variables which are not needed in that question. Every variable (and array) is defined. So don't worry about that.

What i want is to remove the whole <funcgroup siglength="86"> in order to replace it with a different one.

The script works fine, but there is one problem in the output XML. It looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<software>
    <info>
        <version>6.3</version>
        <lasterror>1386680712</lasterror>
    </info>
    <decryption/>
</software>
<funcgroup siglength="86">
<func>
    <name>Nk</name>
    <args>$a</args>
    <code>YYYYY</code>
</func>
<func>
    <name>Ok</name>
    <args>$a,$b</args>
    <code>YYYY</code>
</func>
</funcgroup>

As you can see, the closing software and decryption tags are on the wrong place now.

How can i fix that? I spent hours but can't find a working solution.

The problem is caused by the removeChild() since it works fine if i do not remove something.

查看全部
drqyxkzbs21968684
drqyxkzbs21968684
2013/12/18 14:55
  • dom
  • xml
  • php
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复