Question Everything
Question Everything

Reputation: 2319

How to grep an XML file?

In GNU, how do I grep an XML file? The scenario:

<HelloOperation>
    <Request>Lemon</Request>
</HelloOperation>
<HelloOperation>
    <Request>Banana</Request>
</HelloOperation>
<HelloOperation>
    <Request>Orange</Request>
</HelloOperation>
<DifferentOperation>
    <Request>Banana</Request>
</DifferentOperation>

Any idea how I will grep this such that I will only get the banana inside HelloOperation and not in DifferentOperation? Say for instance I cannot use awk.

Upvotes: 1

Views: 239

Answers (1)

falsetru
falsetru

Reputation: 369444

How about using xmlstartlet? You can select node using XPath.

$ cat 1.xml
<?xml version="1.0"?>
<root>
    <HelloOperation>
        <Request>Lemon</Request>
    </HelloOperation>
    <HelloOperation>
        <Request>Banana</Request>
    </HelloOperation>
    <HelloOperation>
        <Request>Orange</Request>
    </HelloOperation>
    <DifferentOperation>
        <Request>Banana</Request>
    </DifferentOperation>
</root>
$ xmlstarlet sel -t -v './/HelloOperation/Request' 1.xml
Lemon
Banana

Upvotes: 3

Related Questions