How does the shell read the attribute values of XML nodes?

One way to read the attribute values of XML nodes in Shell is to use command line tools like sed and awk. Here is a method using the sed command.

Assume we have an XML file named example.xml, which contains the following content:

<root>
  <node attribute="value1"/>
  <node attribute="value2"/>
</root>

To retrieve the attribute value of a node, you can use the following command:

attribute_value=$(sed -n 's/.*<node attribute="\([^"]*\)".*/\1/p' example.xml)
echo $attribute_value

The output is:

value1
value2

This command uses sed’s regular expressions to match and extract the value of the attribute attribute. Specifically, .*

The above command reads the attribute values of all node nodes and stores them in a variable named attribute_value. To only read the attribute value of the first node node, you can use the following command:

attribute_value=$(sed -n '0,/<node attribute="\([^"]*\)"/ s/.*<node attribute="\([^"]*\)".*/\1/p' example.xml)
echo $attribute_value

The output result is:

value1

Limit the sed command to only match the attribute value of the first node node by adding 0,/

bannerAds