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>
The expected output is:
bob
ailce
ted
carol
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.
I don't know how to achieve what you're trying to achieve with xmllint
only.
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";
}
will output what you want, separated with a nil character.
In a one-liner style:
perl -mXML::XPath -e 'foreach $n (XML::XPath->new(filename => "configurations.xml")->find("//conf/\@name")->get_nodelist) { print $n->getNodeValue,"\0"; }'
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
Note that at this point you have the option of turning to Perl and drop Bash completely to solve your problem.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments