Parse XML with Shell Script

Asked

Viewed 650 times

2

I have the following structure within an XML file:

<TestCase name="A" priority="">
  <Test name="A1" result="pass" />
  <Test name="A2" result="pass"/>
</TestCase>
<TestCase name="B" priority="">
  <Test name="B1" result="pass" />
  <Test name="B2" result="pass"/>
</TestCase>

Using shell script, how do I read and traverse the tags and their subtags, in order to print the result:

A
 A1 - pass
 A2 - pass
B
 B1 - pass
 B2 - pass
  • Which shell? bash? CMD? PS?

  • The shell is bash.

1 answer

1

Your example is not well-formed XML...

To process XML you should use a tool that includes an XML parser. For line command I would suggest something with xmllint or xmlstarlet (there are other excellent)

Using regular expressions can also do anything if the file is very simple and regular. Then goes a Perl example (you can do something similar sed, awk, python) but is attached to the example shown...

perl -nE '/name="(.*?)".*result="(.*?)"/ and say " $1 - $2"  or
          /name="(.*?)"/                 and say $1'    file.xml

Browser other questions tagged

You are not signed in. Login or sign up in order to post.