我正在创建具有条件的xml节点,并且如果节点没有子节点,则想删除它:
<main>
<tags>
<tag></tag>
<tag>hello</tag>
<tag>hello1</tag>
</tags>
</main>
在保存xml之前我想要这个输出:
<main>
<tags>
<tag>hello</tag>
<tag>hello1</tag>
</tags>
</main>
请忽略节点名称:如果我删除它是删除但不删除结束标记,如删除后仍然存在</tag>
:
$doc = new DOMDocument;
$doc->load($path);
$element = $doc->documentElement;
$elementtodelete = $element->getElementsByTagName('OthersInc')->item(0);
if(! $elementtodelete->hasChildNodes()) {
$oldelement = $elementtodelete->parentNode->removeChild($elementtodelete);
}
答案 0 :(得分:0)
检查此代码
<?php
$doc = new DOMDocument;
$doc->preserveWhiteSpace = false;
$doc->loadxml('<main>
<tags>
<tag></tag>
<tag>hello</tag>
<tag>hello1</tag>
</tags>
</main>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//*[not(node())]') as $node ) {
$node->parentNode->removeChild($node);
}
$doc->formatOutput = true;
echo $doc->savexml();
检查您想要的output