0

有没有办法附加一个 SimpleXML 元素的子元素?

例如

<comments>
    <comment1>
        <commentcontent>Test</commentcontent>
    </comment1>
    <comment2>
        <commentcontent>Test2</commentcontent>
        <comment3>
            <commentcontent>Test3</commentcontent>
        </comment3>
    </comment2>
</comments>

我希望comment3 能够对其进行子评论。我在想我可以使用一些正则表达式或通配符来忽略评论元素的数量,但还没有弄清楚如何。

我在尝试

$commentlevel = calculatelevel(($level[$commentkey] - 1)) . 'Comment' . $parent[$commentkey];
$newcomment = $commentsxml->xpath($commentlevel)->addChild('Comment' . $id);

function calculatelevel($level) {
    $compile = '';
    for($inc = 0; $inc < $level; $inc++) {
        $compile = 'Comment*/';
    }
    return $compile;
}

和许多变化,但似乎都失败了。谢谢。

4

1 回答 1

0

如果可以,请“规范化”您的 XML:

<comments>
    <comment id="1" content="Test">
        <comment id="2" content="Hello">
            <comment id="3" content="World">
                <comment id="4" content="It's me!" />
            </comment>
        </comment>
    </comment>
</comments>

子注释很容易,因为您不必关心更改节点名称:

$comment = $xml->xpath("//comment[@id='4']")[0]; // get comment #4 , requires PHP >= 5.4
$newcomment = $comment->addChild('comment');
$newcomment->addAttribute('id', getNewId()); // function getNewId() not specified in this example 
$newcomment->addAttribute('content', 'I am new!'); 

看到它工作:http ://codepad.viper-7.com/K1cxAq

如果您的 PHP < 5.4,请升级或更改此行:

list($comment,) = $xml->xpath("//comment[@id='4']");

如果您无法更改 XML 但必须坚持使用它,请澄清节点名称中数字的含义:它是唯一标识符,还是级别,节点的“深度”?

于 2013-11-05T23:20:45.183 回答