【问题标题】:Remove multiple empty nodes with SimpleXML使用 SimpleXML 删除多个空节点
【发布时间】:2011-04-05 22:58:53
【问题描述】:

我想使用SimpleXML删除我的 XML 文档中的所有空节点

这是我的代码:

$xs = file_get_contents('liens.xml')or die("Fichier XML non chargé");
$doc_xml = new SimpleXMLElement($xs);
foreach($doc_xml->xpath('//*[not(text())]') as $torm)
    unset($torm);   
$doc_xml->asXML("liens.xml");

我通过print_r() 看到 XPath 正在抓取一些东西,但没有从我的 XML 文件中删除。

【问题讨论】:

  • 我不相信您实际上是在 $doc_xml 中的元素上取消设置()。让我查找 SimpleXML 以了解如何正确删除节点。

标签: php xml xpath simplexml


【解决方案1】:
$file  = 'liens.xml';
$xpath = '//*[not(text())]';

if (!$xml = simplexml_load_file($file)) {
    throw new Exception("Fichier XML non chargé");
}

foreach ($xml->xpath($xpath) as $remove) {
    unset($remove[0]);
}

$xml->asXML($file);

【讨论】:

  • dom_import_simplexml()不是必须的,可以直接在simplexml中用unset移除元素节点,不用切换到DOM(simplexml self reference)。
【解决方案2】:

我知道这篇文章有点旧,但在您的foreach 中,$torm 在每次迭代中都会被替换。这意味着您的 unset($torm) 对原始 $doc_xml 对象没有任何作用。

相反,您需要删除元素本身:

foreach($doc_xml->xpath('//*[not(text())]') as $torm)
    unset($torm[0]);
               ###

通过使用 simplxmlelement-self-reference

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 2011-06-20
    • 1970-01-01
    • 1970-01-01
    • 2011-03-25
    相关资源
    最近更新 更多