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.

6
  • Both If conditions in your question are true for the sample XML. What should be the output? Commented Mar 2, 2018 at 9:05
  • I highlighted the output. its two different examples. Commented Mar 2, 2018 at 9:08
  • 1
    Are you asking about how to select a sibling? stackoverflow.com/questions/17040254/… Commented Mar 2, 2018 at 9:19
  • You should probably drop the [linux], [bash] and [shell] tags, imho this is an xpath question. Commented Mar 2, 2018 at 9:19
  • Which kind of command xpath do you have? On my system, I would have to run: xpath -e '//a[text()="01"]/text() | //b' xtest.xml instead. Commented Mar 2, 2018 at 9:55

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The following command worked with XML as file.xml

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

2 Comments

This doesn't work on Ubuntu with xpath installed along with libxml-xpath-perl. Probably, you have another flavour of xpath.
This is suse linux
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.