You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让xmllint输出的匹配结果带分隔符(RHEL7环境)

为xmllint的XPath输出添加分隔符(RHEL7环境)

问题场景

给定XML内容:

<parent>
   <child>test1</child>
   <child>test2</child>
</parent>

执行命令 xmllint --format --xpath '//parent/child/text()' - 提取child节点文本时,输出结果为test1test2,节点文本直接拼接无分隔符,无法在管道中循环处理单个结果,需要添加指定分隔符(如test1-test2或test1 test2)。

解决方案

以下是几种基于RHEL7默认工具的实现方式:

方法1:结合sed处理节点输出

先提取完整的child节点,再通过sed替换标签并添加分隔符:

xmllint --xpath '//parent/child' input.xml | sed -e 's/<\/child>/-/g' -e 's/<child>//g' -e 's/-$//'
  • 说明:将</child>替换为分隔符-,移除<child>标签,最后删除末尾多余的分隔符;若需要空格分隔,将s/<\/child>/-/g改为s/<\/child>/ /g即可。

方法2:利用xmllint shell模式拆分输出

通过xmllint的交互shell模式逐个输出节点文本,再统一处理分隔符:

echo 'cat //parent/child/text()' | xmllint --shell input.xml | grep -v "^/" | tr '\n' '-' | sed 's/-$//'
  • 说明:grep -v "^/"过滤掉shell模式的无关提示符,tr '\n' '-'将每行的节点文本用-连接,最后清理末尾分隔符;更换分隔符只需修改tr的目标字符。

内容的提问来源于stack exchange,提问作者Sven van den Boogaart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:12:34