brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: xmlstarlet sel -t -v pulls values out of XML with an XPath

Xml
~/tips/tip-xmlstarlet-sel-value-of

xmlstarlet sel -t -v '//item/title' -n feed.xml

Read single values from an XML file with an XPath, from the command line.

Parsing XML with grep and sed ends badly. When I need one value from a feed or a config file, I’d rather use a real XPath.

xmlstarlet sel runs an XPath query. -t starts a template, -v prints the value and -n adds a newline:

xmlstarlet sel -t -v '//item/title' -n feed.xml

With a file that has two items, that prints the two titles on their own lines. To print several values per match, loop with -m and add text between them with -o:

xmlstarlet sel -t -m '//item' -v '@id' -o ': ' -v title -n feed.xml

That gives lines such as 1: A and 2: B. XPath functions work too: -v "count(//item)" counts the items.

A caveat: a document with a default namespace makes a plain XPath match nothing. Predefine the namespace with -N and use its prefix in the query. The package is called xmlstarlet, and the command is xmlstarlet on Debian and Ubuntu.

Further reading: XMLStarlet user guide

More Xml tips xmlstarlet ed -u '//item[@id="1"]/title' -v 'Changed' feed.xml All Xml tips (2) All topics

Link