[英]PHP Remove Empty Node Values From XML
我已經生成了一個xml。 我要刪除的空節點很少
我的XML
https://pastebin.com/wzjmZChU
我想從xml中刪除所有空節點。 使用我嘗試過的xpath
$xpath = '//*[not(node())]';
foreach ($xml->xpath($xpath) as $remove) {
unset($remove[0]);
}
上面的代碼在一定程度上可以正常工作,但是我無法刪除所有空節點值。
編輯
我已經嘗試了上面的代碼,它僅適用於單個級別。
您認為沒有子元素為空//*[not(node())]
任何元素節點都將完成此操作。 但是,如果刪除了元素節點,則可能會導致其他空節點,因此您將需要一個表達式,該表達式不僅要刪除當前為空的元素節點,而且還要刪除那些僅具有空后代節點的對象(遞歸)。 另外,您可能希望避免刪除document元素,即使該元素為空也可能會導致無效的文檔。
/*
/*//*
/*//*[normalize-space(.) = ""]
/*//*[normalize-space(.) = "" and not(@*)]
/*//*[normalize-space(.) = "" and not(@* or .//*[@*])]
/*//*[normalize-space(.) = "" and not(@* or .//*[@*] or .//comment())]
/*//*[ normalize-space(.) = "" and not(@* or .//*[@*] or .//comment() or .//processing-instruction()) ]
以相反的順序迭代結果,以便在父節點之前刪除子節點。
$xmlString = <<<'XML'
<foo>
<empty/>
<empty></empty>
<bar><empty/></bar>
<bar attr="value"><empty/></bar>
<bar>text</bar>
<bar>
<empty/>
text
</bar>
<bar>
<!-- comment -->
</bar>
</foo>
XML;
$xml = new SimpleXMLElement($xmlString);
$xpath = '/*//*[
normalize-space(.) = "" and
not(
@* or
.//*[@*] or
.//comment() or
.//processing-instruction()
)
]';
foreach (array_reverse($xml->xpath($xpath)) as $remove) {
unset($remove[0]);
}
echo $xml->asXml();
輸出:
<?xml version="1.0"?>
<foo>
<bar attr="value"/>
<bar>text</bar>
<bar>
text
</bar>
<bar>
<!-- comment -->
</bar>
</foo>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.