xml_grep to get related info in stanza

Viewed 82

XML noob here.

If a stanza has <favorite>true</favorite> i want to only print the info in <path>XXXX</path>

I've been banging my head against the wall with xml_grep & xmllint trying to extract what i feel is a very simple amount of information. Maybe these are the wrong tools? would some python just be the easiest way to go about this? i have no idea how to write that, though

<fileList>
    <file>
            <path>./filename.zip</path>
            <name>My Filename</name>
            <favorite>true</favorite>
            <lastaccessed>20210406T130359</lastaccessed>
    </file>
</fileList>
2 Answers

You can use xmlstarlet for that.

Here is snippet that gives only the required paths:

xmlstarlet sel --template --match "/fileList/file[favorite = 'true']" --value-of ./path --nl my_xml_file.xml

For example, if the contents of my_xml_file.xml are:

<fileList>
    <file>
            <path>./filename.zip</path>
            <name>My Filename</name>
            <favorite>true</favorite>
            <lastaccessed>20210406T130359</lastaccessed>
    </file>
    <file>
            <path>./filename2.zip</path>
            <name>My Filename</name>
            <favorite>false</favorite>
            <lastaccessed>20210406T130359</lastaccessed>
    </file>
</fileList>

This command returns:

./filename.zip

With it's as simple as:

xidel -s "input.xml" -e '//file[favorite="true"]/path'
Related