【问题标题】:How to check if an attribute is present in an xml node using xmllint如何使用 xmllint 检查 xml 节点中是否存在属性
【发布时间】:2021-06-06 20:25:51
【问题描述】:

我正在使用bashxmllint 来检查以下xml 中的节点:

<?xml version="1.0" encoding="utf-8"?>
<output>
<document>
    <sentence id="13">
        <text>This is a test sentence.</text>
        <entities>
            <annotation id="3">
                <grammar-form id="0" normal-form="THIS"/>
            </annotation>
            <annotation id="4">
                <grammar-form id="0" normal-form="IS"/>
            </annotation>
            <annotation id="5">
                <grammar-form id="0" normal-form="A"/>
            </annotation>
            <annotation id="6">
                <grammar-form id="0" normal-form="TEST"/>
            </annotation>
            <annotation id="7">
                <grammar-form id="0" normal-form="SENTENCE"/>
            </annotation>
            <annotation id="12">
                <grammar-form id="0" normal-form="."/>
            </annotation>
        </entities>
    </sentence>
</document>
</output>

如何简单地检查每个grammar-form 节点是否存在normal-form 属性?属性值是什么并不重要,我只需要检查它是否存在。

【问题讨论】:

  • 我们鼓励提问者展示他们迄今为止为自己解决问题所做的尝试。

标签: bash xmllint


【解决方案1】:

选择grammar-forms 具有该属性并查看是否有任何匹配项更容易:

if xmllint --xpath '//grammar-form[not(@normal-form)]' input.xml 1>/dev/null 2>&1; then
    echo "There are missing normal forms."
else
    echo "There are no missing normal forms."
fi

在 xpath 模式下,xmllint 将打印匹配的路径,或者如果没有匹配的路径,则以错误代码 10 退出并打印一条消息到标准错误(手册页中提到的 --noout 选项以抑制不幸的是,输出在我正在测试的版本中没有做任何事情),因此重定向。

【讨论】:

    猜你喜欢
    • 2023-04-03
    • 2020-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    相关资源
    最近更新 更多