bash 使用 xmllint 提取 xml 属性值

bash extract xml attribute value using xmllint

我正在从 xml 文件中提取属性值,但出现错误。 我想在 firstpart 元素中提取 key="qua" 的值。这是我的脚本,但您会在下面发现错误:

#!/bin/bash

myfile=

myvar=$(echo 'cat //firstpart/step/category/id/info[@key="qua"]/@value' | xmllint --xpath "$myfile" | awk -F'[="]' '!/>/{print $(NF-1)}')

echo "$myvar"

我的 xml 文件长什么样:

<?xml version='1.0' encoding='UTF-8'?>
<firstpart>
    <step name="Home">    
        <category name="one">
            <id name="tools">
                <info key="qua" value="1"/>        
            </id>
        </category>
    </step>
    <step name="Contact">    
        <category name="two">
            <id name="tools">
                <info key="qua" value="2"/>        
            </id>
        </category>
    </step>
    ...
</firstpart>
<secondpart>
    <step name="office">    
        <category name="one">
            <id name="tools">
                <info key="qua" value="100"/>        
            </id>
        </category>
    </step>
    <step name="Contact">    
        <category name="two">
            <id name="tools">
                <info key="qua" value="200"/>        
            </id>
        </category>
    </step>
    ...
</secondpart>

我得到的错误:

awk: run time error: negative field index $-1
    FILENAME="-" FNR=71 NR=71

./mybash.sh: line 3: $: command not found
./mybash.sh: line 4: $: command not found

看来你调用 xmllint 的方式有误。

xmllint --xpath '//firstpart/step/category/id/info[@key="qua"]/@value' FILE.xml

结果:

value="1" value="2"

完整脚本:

#!/bin/bash

str=$(xmllint --xpath '//firstpart/step/category/id/info[@key="qua"]/@value' )

entries=($(echo ${str}))
for entry in "${entries[@]}"; do
    result=$(echo $entry | awk -F'[="]' '!/>/{print $(NF-1)}')
    echo "result: $result"
done

可能不是更好的解决方案,但至少它有效:)

使用 xmllint 获取属性值:

xmllint --xpath 'string(//firstpart/step[1]/category/id/info/@value)' file.xml

输出:

1