xml - 使用 xmllint 根据另一个标签限定符的值提取标签内容
问题描述
如果前一个标签上存在条件,我正在尝试使用 xmllint 从标签中提取数据。我知道可能有更好的工具,但我仅限于 xmllint 和/或系统标准命令,如 sed、awk 等。
xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<MainGroup>
<MainGroupEntry name="aaa" function="xxx">
<EntryType type="AAA"/>
<EntryDescription>Capture This A</EntryDescription>
<EntryRandomList>Just,a,random,list,of,things,to,discard</EntryRandomList>
</MainGroupEntry>
<MainGroupEntry name="aaa" function="xxx">
<EntryType type="AAA"/>
<EntryDescription>Capture This A</EntryDescription>
<EntryRandomList>Just,a,random,list,of,things,to,discard</EntryRandomList>
</MainGroupEntry>
<MainGroupEntry name="bbb" function="yyy">
<EntryType type="BBB"/>
<EntryDescription>Capture This B</EntryDescription>
<EntryRandomList>Just,a,random,list,of,things,to,discard</EntryRandomList>
</MainGroupEntry>
<MainGroupEntry name="bbb" function="yyy">
<EntryType type="BBB"/>
<EntryDescription>Capture This B</EntryDescription>
<EntryRandomList>Just,a,random,list,of,things,to,discard</EntryRandomList>
</MainGroupEntry>
</MainGroup>
我“试图做的是;对于每个Entry type="AAA"
,打印随附的EntryDescription
。我尝试了不同的变体:xmllint --xpath '//MainGroupEntry/EntryType[@type="AAA"]/EntryDescription/text()' my_file.xml
但我总是得到一个空的 XPath 集。如果我放弃尝试获取描述文本,我可以看到以下条目匹配我的“类型”条件:
xmllint --xpath '//MainGroupEntry/EntryType[@type="AAA"]' my_file.xml
<EntryType type="AAA"/><EntryType type="AAA"/>
我似乎无法弄清楚如何只从描述字段中获取文本。想法?
解决方案
您可以使用following-sibling
轴和text()
函数仅从描述中提取文本:
xmllint --xpath '/MainGroup/MainGroupEntry/EntryType[@type="AAA"]/following-sibling::EntryDescription/text()' file.xml
要分隔文本,您可以使用以下--shell
选项cat
:
echo 'cat /MainGroup/MainGroupEntry/EntryType[@type="AAA"]/following-sibling::EntryDescription/text()' \
| xmllint --shell file.xml
您可能需要| grep -v ' -----\|/ >'
输出来删除分隔符和提示。
推荐阅读
- reactjs - 功能组件接收道具但不渲染它
- c# - 网络文件夹上的 Directory.GetFiles
- html - 如何通过在 Angular Material 表单的任何字段中按 Enter 键来提交表单?
- python - 'NoneType' 对象在比较 python 中的 2 个列表时没有属性 'sort'
- c++ - c++ 中箭头运算符“->”的意外行为
- python - 在 ubuntu 中从 python 运行 powershell 模块
- java - 无法使用 SpringBoot 发送 Post 请求
- swift - Swift:var a: Int { calculateValue() } 和 var b = { calculateValue() }() 之间的区别
- python - 如何获取包含完整路径和扩展名的所有文件名的列表
- c++ - 如何在另一个类/结构类型中初始化类/结构类型的成员