如何使用xmlstarlet编辑XML节点的文本或HTML内容?
问题背景与需求
此前的问题《如何使用xmlstarlet访问带引号的XML节点》展示了通过命名空间访问XML节点并删除整个节点的方法,对应命令为:xmlstarlet edit -N ns="http://www.w3.org/2005/Atom" -d "//ns:content[@type='html']" input.xml > output.xml
现在需要实现编辑<content type='html'>节点内容的操作:删除该节点内所有HTML标签,仅保留纯文本内容。
输入文件input.xml内容
<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:blogger="http://schemas.google.com/blogger/2018"> <title>Testv1</title> <entry> <author> <name>Author</name> </author> <title/> <content type='html'><p>Test Post 2</p><p></p><p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem, eaque ipsa quae voluptas nulla pariatur?</p><p></p><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/kitten2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="360" data-original-width="360" height="320" src="https://blogger.googleusercontent.com/kitten2.png" width="320" /></a></div><br /><p></p><p></p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</content> </entry> <entry> <author> <name>Author</name> </author> <title/> <content type='html'>....</content> </entry>
期望输出output.xml内容
<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:blogger="http://schemas.google.com/blogger/2018"> <title>Testv1</title> <entry> <author> <name>Author</name> </author> <title/> <content type='html'>Test Post 2 Sed ut perspiciatis unde omnis iste natus error sit voluptatem, eaque ipsa quae voluptas nulla pariatur? Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor</content> </entry> <entry> <author> <name>Author</name> </author> <title/> <content type='html'>....</content> </entry>
请问是否可以使用xmlstarlet实现该节点编辑操作?
解决方案
可以用xmlstarlet实现这个需求,核心思路是提取目标节点下的所有文本内容,再用清理后的纯文本替换原节点内容。具体命令如下:
xmlstarlet edit -N ns="http://www.w3.org/2005/Atom" \ --update "//ns:content[@type='html']" \ --value "$(xmlstarlet sel -N ns="http://www.w3.org/2005/Atom" -t -m "//ns:content[@type='html']" -v "normalize-space(.)" input.xml)" \ input.xml > output.xml
命令解释
- 命名空间声明:
-N ns="http://www.w3.org/2005/Atom"指定Atom命名空间,确保能精准定位目标节点。 - 更新节点操作:
--update "//ns:content[@type='html']"选中所有符合条件的<content>节点。 - 提取并清理文本:
- 嵌套的
xmlstarlet sel命令通过normalize-space(.)提取目标节点下的全部文本,同时自动去除多余的换行、空格,将零散文本合并为连续的纯文本。 - 把处理后的纯文本作为
--value的值,覆盖原节点的内容。
- 嵌套的
效果说明
执行该命令后,所有<content type='html'>节点内的HTML标签会被完全移除,仅保留合并后的纯文本内容,与期望输出一致。
内容的提问来源于stack exchange,提问作者user5853892
相关产品推荐
相关产品推荐

