drsl90685154 2014-08-25 18:35
浏览 57
已采纳

删除XPath中的自关闭标记

I have used this solution to remove empty tags from my generated XML.

Remove empty tags from a XML with PHP

However, if the generated XML has nested nodes that are empty, for example:

<metro>
   <distance></distance>
   <name></name>
</metro>

Then the result for that portion will be

<metro/>

Is there a way to remove those self-closing tags?

  • 写回答

2条回答 默认 最新

  • dongmei2956 2014-08-25 19:46
    关注

    A simple modification to the XPath you referenced should accomplish what you need:

    //*[not(normalize-space())]
    
    foreach( $xpath->query('//*[not(normalize-space())]') as $node ) {
        $node->parentNode->removeChild($node);
    }
    

    The answer in the question you linked to can be interpreted as "Match all elements that do not have a child node". metro has five child nodes, so that XPath does not match it.

    The XPath in my answer can be interpreted as "Match all elements that do not contain any non-whitespace text."

    I suggest you read up on normalize-space() if you are unfamiliar with it, but basically in this case, it produces an empty string if all the text nodes within an element are whitespace, so in the case of metro we have:

    not(normalize-space())
    
    not(normalize-space(.))  // If no argument is specified, the context node is used.
    
    not(normalize-space("    // normalize-space() expects a string, so the nodeset . is 
                             // replaced with its string-value (all the text it contains).
    
    
    "))
    
    not("")                  // normalize-space() eliminates all leading and trailing
                             // whitespace.
    
    not(false())             // not() expects a boolean, and the boolean equivalent of
                             // the empty string is false()
    
    true()
    

    Since the predicate evaluates to true(), metro is selected.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算