0

When I have an XML file like this:

<guests>
    <guest>
        <name>Adam</name>
        <music>Silence</music>
        <dish>Vegetables</dish>
        <beverage>Water</beverage>
    </guest>
    <guest>
        <name>Brutus</name>
        <music>Verdi</music>
        <dish>Meat</dish>
        <beverage>Mulsum</beverage>
    </guest>
</guests>

Is there already an elegant bash-y way of formatting this into a table? I imagine it like this:

cat myPartyGuests.xml | xmlToTable --lines "/guests/guest" --columns "name, beverage, dish"

that gives something like this:

name   beverage dish
Adam   Water    Vegetables
Brutus Mulsum   Meat

I already know that if I could get the XML into a form like this:

name;beverage;dish
Adam;Water;Vegetables
Brutus;Mulsum;Meat

...I can use column -s\; -t to get exactly my desired output, so only the "XML to CSV" step is missing.

1 Answer 1

1

One solution would be to use XSL transformations using XSL stylesheets.

Or write a simple Python script:

#!/usr/bin/env python3

import untangle, sys

data = untangle.parse(sys.stdin.read())

print(" ".join(["name", "beverage", "dish"]))
for guest in data.guests.guest:
    print(" ".join([guest.name.cdata, guest.beverage.cdata, guest.dish.cdata]))

Install untangle with pip3 install --user untangle, make the script executable, and run:

$ ./test.py < myPartyGuests.xml
Adam Water Vegetables
Brutus Mulsum Meat

Or use xmltodict:

#!/usr/bin/env python3

import xmltodict, sys

data = xmltodict.parse(sys.stdin.read())

fields = ["name", "beverage", "dish"]

print(" ".join(fields))
print("\n".join(" ".join(guest[f] for f in fields) for guest in data["guests"]["guest"]))

I'm using untangle or xmltodict instead of builtin XML libraries because I find those easier to use. This can be done with any other scipting language, of course.

1
  • This is cool!! :-) I am thinking of making a generic version of that, but I do not have the time now. Just great. =)
    – Bowi
    Nov 21, 2019 at 16:03

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .