簡體   English   中英

PHP從XML刪除空節點值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM