1

I have an XML as follows

<demos>
 <demo>
  <a>00</a>
  <b>First</b>
  <c>ProjectA</c>
 </demo>
 <demo>
  <a>01</a>
  <b>Second</b>
  <c>ProjectB</c>
 </demo>
</demos>

Example 1: If within <a> tag has 00 and <c> tag has ProjectA, Output should be First

Example 2: If within <a> tag has 01 and <c> tag has ProjectB, Output should be Second

I want try with xml_grep or xpath as these are installed packages in linux by default. I tried different ways such as

xpath xtest.xml '//a[text()="01"]/text() | //b'

but this validation doesnt work.

3 Answers3

1

For example 1, you will have to run:

xpath -q -e '//demo[(a/text()="00") and (c/text()="ProjectA")]/b/text()' xtest.xml

For example 2:

xpath -q -e '//demo[(a/text()="01") and (c/text()="ProjectB")]/b/text()' xtest.xml

Be aware that xpath is not installed by default on any Linux. On Ubuntu, you will first have to run sudo apt install libxml-xpath-perl.

Pierre François
  • 5,850
  • 1
  • 17
  • 38
0

The following command worked with XML as file.xml

 xpath file.xml '//demo[a/text()="00" and c/text()="ProjectA"]/b/text()'
0

Robust xmlstarlet solution:

xmlstarlet sel -t -m '//demo/a' --if '. = 00 and ./following-sibling::c="ProjectA"' \
-v './following-sibling::b' -n input.xml

The output:

First

xmlstarlet sel -t -m '//demo/a' --if '. = 01 and ./following-sibling::c="ProjectB"' \
-v './following-sibling::b' -n input.xml

The output:

Second
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105