如何用XPath与xmlstarlet删除不含three子元素的two元素?
使用xmlstarlet删除不含子元素的节点
问题场景
现有some.xml文件,内容如下:
<one> <two> <three> <four>some text</four> </three> </two> <two> <three> <four>some other text</four> </three> </two> <two> </two> </one>
此前可以通过文本匹配删除特定<two>元素,比如下面的命令会删除包含some text的第一个<two>节点:
xmlstarlet ed -d "//one/two[contains(.,'some text')]" some.xml
现在需要实现的是:删除所有不包含<three>子元素的<two>元素,最终得到如下结构:
<one> <two> <three> <four>some text</four> </three> </two> <two> <three> <four>some other text</four> </three> </two> </one>
解决命令
使用XPath的not()函数定位目标节点,执行删除操作:
xmlstarlet ed -d "//one/two[not(three)]" some.xml
说明
XPath表达式//one/two[not(three)]会匹配所有属于<one>节点下、没有直接<three>子元素的<two>节点,执行该命令后即可得到期望的XML结构。
内容的提问来源于stack exchange,提问作者ospf
相关产品推荐
相关产品推荐

