Shellscript读取XML属性值 [英] Shellscript Read XML attribute value
问题描述
我们想从XML文件中读取XML属性.文件内容示例如下:
We want to read XML attributes from an XML file. Example of file content is as below:
<properties>
<property name="abc" value="15"/>
<property name="xyz" value="26"/>
</properties>
我们要使用shell脚本读取属性"abc"的值(即15).
请建议使用shell命令来实现此目的.
We want to read value (i.e. 15) for property "abc" using shell script.
Please suggest shell commands to achieve this.
推荐答案
您可以使用适当的XML解析器,例如xmllint.如果您的版本支持xpath,将很容易获取特定值.如果它不支持xpath,则可以使用--shell
选项,如下所示:
You can use a proper XML parser like xmllint. If your version supports xpath, it will be very easy to grab specific values. If it doesn't support xpath, then you can use --shell
option like so:
$ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml
/ > -------
value="15"
/ >
然后可以使用awk
或sed
格式化并从输出中提取所需的字段.
You can then use awk
or sed
to format and extract desired field from output.
$ echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxmlfile | awk -F'[="]' '!/>/{print $(NF-1)}'
15
您可以使用命令替换通过说出以下内容来捕获变量中的输出:
You can use command substitution to capture the output in a variable by saying:
$ myvar=$(echo 'cat //properties/property[@name="abc"]/@value' | xmllint --shell myxml | awk -F'[="]' '!/>/{print $(NF-1)}')
$ echo "$myvar"
15
使用xmlparser以外的其他任何内容都容易出错,并且很容易出错.
Using anything else other than a xmlparser is prone to errors and will break easy.
这篇关于Shellscript读取XML属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!