Bowi
Bowi

Reputation: 1528

Select multiple elements with xmlstarlet

Since I could not find an explained example elsewhere, I share my findings as a Q&A.

Consider this list of pupils (pupils.xml):

<pupils>
    <pupil>
        <firstName>Adam</firstName>
        <lastName>Amith</lastName>
        <birthDate>2000-01-01</birthDate>
    </pupil>
    <pupil>
        <firstName>Berta</firstName>
        <lastName>Bmith</lastName>
        <birthDate>2000-01-02</birthDate>
    </pupil>
    <pupil>
        <firstName>Caesar</firstName>
        <lastName>Cmith</lastName>
        <birthDate>2000-01-03</birthDate>
    </pupil>
    <pupil>
        <firstName>Doris</firstName>
        <lastName>Dmith</lastName>
        <birthDate>2000-01-04</birthDate>
    </pupil>
</pupils>

How can I select two subattributes of each pupil to get a list like this:

Adam Amith
Berta Bmith
Caesar Cmith
Doris Dmith

Upvotes: 4

Views: 1708

Answers (2)

Jack Fleeting
Jack Fleeting

Reputation: 24930

You can also use concat() here:

xmlstarlet sel -T -t -m //pupil -v "concat(.//firstName ,' ',.//lastName)" -n pupils.xml

with the same output.

Upvotes: 3

Bowi
Bowi

Reputation: 1528

The command to get this is

xmlstarlet select -T -t -m "//pupil" -v "firstName" -o " " -v "lastName" -n pupils.xml

and brings:

Adam Amith
Berta Bmith
Caesar Cmith
Doris Dmith
  • -T switches the output to text
  • -t -m "//pupil" -v "firstName" -o " " -v "lastName" -n defines a template
    • -m "//pupil" matches every pupil node
    • -v "firstName" prints the value of the firstName subnode (subnode of currently matched node)
    • -o " " prints a blank
    • -v "lastName" (see above)
    • -n prints a newline
  • pupils.xml provides the input file

The documentation provides even more advanced parameters.

Upvotes: 7

Related Questions