bash 如何使用 xmllint 解析 xml 并存储在数组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21293364/
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
How to parse xml using xmllint and store in arrays
提问by JVK
In shell script, I have an xml file as p.xml, as follows and I want to parse it and get values in two arrays. I am trying to use xmllint, but could not get desired data.
在 shell 脚本中,我有一个 xml 文件作为 p.xml,如下所示,我想解析它并获取两个数组中的值。我正在尝试使用 xmllint,但无法获得所需的数据。
<?xml version="1.0" encoding="UTF-8"?>
<Share_Collection>
<Share id="data/Backup" resource-id="data/Backup" resource-type="SimpleShare" share-name="Backup" protocols="cifs,afp"/>
<Share id="data/Documents" resource-id="data/Documents" resource-type="SimpleShare" share-name="Documents" protocols="cifs,afp"/>
<Share id="data/Music" resource-id="data/Music" resource-type="SimpleShare" share-name="Music" protocols="cifs,afp"/>
<Share id="data/OwnCloud" resource-id="data/OwnCloud" resource-type="SimpleShare" share-name="OwnCloud" protocols="cifs,afp"/>
<Share id="data/Pictures" resource-id="data/Pictures" resource-type="SimpleShare" share-name="Pictures" protocols="cifs,afp"/>
<Share id="data/Videos" resource-id="data/Videos" resource-type="SimpleShare" share-name="Videos" protocols="cifs,afp"/>
</Share_Collection>
I want to get an array all share ids and one array containing share-names. So two array would be like
我想得到一个包含共享名的数组和一个包含共享名的数组。所以两个数组会像
share-ids-array = ["data/Backup", "data/Documents", "data/Music", "data/OwnCloud", "data/Pictures", "data/Videos"]
share-names-array = ["Backup", "Documents", "Music", "OwnCloud", "Pictures", "Videos"]
I started as follows:
我开始如下:
xmllint --xpath '//Share/@id' p.xml
xmllint --xpath '//Share/@share-name' p.xml
that gives me
这给了我
id="data/Backup"
id="data/Documents" id="data/Music" id="data/OwnCloud" id="data/Pictures" id="data/Videos"
Any help to build those two arrays will be appreciated.
任何构建这两个数组的帮助将不胜感激。
回答by bryn
Here is one solution with grep (and tr)...sed or awk are other alternatives. By the way, you cannot use hyphens in variable names in bash.
这是 grep(和 tr)的一种解决方案……sed 或 awk 是其他选择。顺便说一下,你不能在 bash 的变量名中使用连字符。
share_ids=($( xmllint --xpath '//Share/@id' p.xml | grep -Po '".*?"' | tr -d \" ))
share_names=($( xmllint --xpath '//Share/@share-name' p.xml | grep -Po '".*?"' | tr -d \" ))
Example:
例子:
$ echo ${share_names[@]}
Backup Documents Music OwnCloud Pictures Videos
Using xmlstarletis probably better, though:
不过,使用xmlstarlet可能更好:
share_names=($( xmlstarlet sel -T -t -m '//Share/@share-name' -v '.' -n p.xml ))