Mowgli Mowgli - 7 months ago 22
Bash Question

Shell script to retrieve node NAME from XML file

I have a XML file like below, I am trying to retrieve the first child node name and store it in an array and use it for reading the attributes.

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="config.xsl"?>
<cell name="servicesPrd">
<env>Prod </env>
<console>
...
</console>
<vhosts>
....
</vhosts>
<clusters>
....
</clusters>
<nodes>
....
</nodes>
</cell>


I am looking to retrieve env, console, vhosts, cluster, nodes through shell script

BTW I am able to read the node attributes using xmllint which is working fine, currently hardcoded the nodenames to it.

Answer

xmlstarlet is generally useful for querying XML files:

$ xmlstarlet sel -t -m '/cell/*' -v 'name()' -n your.xml
env
console
vhosts
clusters
nodes

$ xmlstarlet el your.xml
cell
cell/env
cell/console
cell/vhosts
cell/clusters
cell/nodes