简体   繁体   English

bash使用xmllint提取xml属性值

[英]bash extract xml attribute value using xmllint

I am extracting an attribute value from xml file, but I get an error. 我正在从xml文件提取属性值,但出现错误。 I'd like to extract the value for key="qua" in the firstpart element. 我想在第一部分元素中提取key="qua" 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"

how my xml file looks like: 我的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>

the errors I get: 我得到的错误:

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

It looks like you call xmllint in wrong way. 看来您以错误的方式调用xmllint

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

Result: 结果:

value="1" value="2"

Complete script: 完整的脚本:

#!/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 :) 可能是,这不是更好的解决方案,但至少它可以工作:)

Get value of attribute with xmllint: 使用xmllint获取属性的值:

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

Output: 输出:

1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM