如何使用xmllint/xpath解析不同元素上几个属性的值? [英] How to parse out the value of several attributes on different elements with xmllint/xpath?
问题描述
对于给定的名为 configurations.xml 的xml文件,我想提取每个conf
元素的 value ,并将其存储在变量中以备后用.
For a given xml file called configurations.xml I would like to extract the value of each conf
element, and store it in a variable for later use.
<configurations>
<conf name="bob"/>
<conf name="alice"/>
<conf name="ted"/>
<conf name="carol"/>
</configurations>
预期输出为:
bob
ailce
ted
carol
我有 xpath 和 xmllint 可用. //conf/@name
的xpath获取节点,但输出为name="bob"
,这是我要避免的事情.
I have xpath and xmllint available. A xpath of //conf/@name
gets the nodes, but outputs as name="bob"
, which is what I'm trying to avoid.
推荐答案
我不知道如何仅使用xmllint
来实现您要实现的目标.
I don't know how to achieve what you're trying to achieve with xmllint
only.
由于已安装xpath
,所以您也安装了Perl的XML::XPath
.那么一点点Perl:
Since you have xpath
installed, you have Perl's XML::XPath
too. So a little bit of Perl:
#!/usr/bin/perl
use XML::Path;
my $xp=XML::XPath->new(filename => 'configurations.xml');
my $nodeset=$xp->find('//conf/@name');
foreach my $node ($nodeset->get_nodelist) {
print $node->getNodeValue,"\0";
}
将输出所需的内容,并用nil字符分隔.
will output what you want, separated with a nil character.
单线样式:
perl -mXML::XPath -e 'foreach $n (XML::XPath->new(filename => "configurations.xml")->find("//conf/\@name")->get_nodelist) { print $n->getNodeValue,"\0"; }'
例如在Bash数组中检索它们:
To retrieve them in, e.g., a Bash array:
#!/bin/bash
names=()
while IFS= read -r -d '' n; do
names+=( "$n" )
done < <(
perl -mXML::XPath -e 'foreach $n (XML::XPath->new(filename => "configurations.xml")->find("//conf/\@name")->get_nodelist) { print $n->getNodeValue,"\0" }'
)
# See what's in your array:
display -p names
请注意,此时您可以选择使用Perl并完全删除Bash来解决问题.
Note that at this point you have the option of turning to Perl and drop Bash completely to solve your problem.
这篇关于如何使用xmllint/xpath解析不同元素上几个属性的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!