本文介绍了bash使用xmllint提取xml属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am extracting an attribute value from xml file, but I get an error.I'd like to extract the value for key="qua" in the firstpart element. Here is my script, but below you find the errors:

#!/bin/bash

myfile=$1

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

echo "$myvar"

我的xml文件的样子:

how my xml file looks like:

<?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 .

It looks like you call xmllint in wrong way.

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' $1)

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

也许是,这不是更好的解决方案,但至少它可以工作:)

May be, it's not better solution, but at least it works :)

这篇关于bash使用xmllint提取xml属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 12:07