Converting XML to CSV

Published: Friday, Aug 21, 2009 Last modified: Monday, Jul 15, 2024 contains some unstructured data that we can simplify in a Comma-separated values file.

curl -s | xmlstarlet sel -t -m '//test' -v '@for' -o ',' -v '@src' -n

So what are we doing? First we rip out all the tests with the Xpath match -m '//test'

curl -s | xmlstarlet sel -t -m '//test' -v '.' -n

Then we snag individiaul values with -v. @for selects “foo” for the attribute for=“foo”. If it was ‘.’ it would select the innerText of the test element.

-o ',' inserts the comma and -n simply outputs a new line.

xmlstarlet is quite ok once you starting using it. Search code search for more examples.