A pure bash
function, just for the unfortunate case when you are not allowed to install anything appropriate. This may, and probably will, fail on more complicated XML:
function xmlpath()
{
local expr="${1//\// }"
local path=()
local chunk tag data
while IFS='' read -r -d '<' chunk; do
IFS='>' read -r tag data <<< "$chunk"
case "$tag" in
'?'*) ;;
'!–-'*) ;;
'![CDATA['*) data="${tag:8:${#tag}-10}" ;;
?*'/') ;;
'/'?*) unset path[${#path[@]}-1] ;;
?*) path+=("$tag") ;;
esac
[[ "${path[@]}" == "$expr" ]] && echo "$data"
done
}
Usage:
bash-4.1$ xmlpath 'config/global/resources/default_setup/connection/host' < MagePsycho.xml
localhost
Known issues:
- slow
- searches only by tag names
- no character entity decoding