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 求chat4.0解答一道线性规划题,用lingo编程运行,第一问要求写出数学模型和lingo语言编程模型,第二问第三问解答就行,我的ddl要到了谁来求了
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果