首页 > 解决方案 > 使用 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"/>

我似乎无法弄清楚如何只从描述字段中获取文本。想法?

标签: xmlxml-parsingxmllint

解决方案


您可以使用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 ' -----\|/ >'输出来删除分隔符和提示。


推荐阅读