bash 使用 xmllint 提取 xml 属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43870622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash extract xml attribute value using xmllint
提问by passion
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 firstpartelement. Here is my script, but below you find the errors:
我正在从 xml 文件中提取一个属性值,但出现错误。我想提取值key="qua"
的firstpart元素。这是我的脚本,但在下面您会发现错误:
#!/bin/bash
myfile=
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
回答by Bor Laze
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' )
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 :)
可能是,这不是更好的解决方案,但至少它有效:)
回答by Cyrus
Get value of attribute with xmllint:
使用 xmllint 获取属性值:
xmllint --xpath 'string(//firstpart/step[1]/category/id/info/@value)' file.xml
Output:
输出:
1