How to get XMLLINT to put --xpath results as an array How to get XMLLINT to put --xpath results as an array bash bash

How to get XMLLINT to put --xpath results as an array


The smallest change needed to make your existing code work is to add parens before the [$i], like so:

#!/usr/bin/bashwwCount=$(xmllint --xpath 'count(//absolutePath)' "mcv.xml")for ((i=1; i<=wwCount; i++)); do        wwExtracted=$(xmllint --xpath '(//absolutePath)['"$i"']/text()' "mcv.xml")        printf " - absolutePath: '%s' \n" "$wwExtracted"        printf " - index: '%d' \n" "$i"done 

That said, this is really inefficient (running your XPath over and over). Consider switching away from xmllint to use XMLStarlet instead, which can be instructed to insert newlines between output elements, so you can tell bash to load those items directly into a real shell array:

#!/usr/bin/bashreadarray -t items < <(xmlstarlet sel -t -m '//absolutePath' -v './text()' -n <mcv.xml)printf ' - absolutePath: %s\n' "${items[@]}"

Once you've got contents into an array (as created by readarray above), you can also iterate by index:

for idx in "${!items[@]}"; do  printf ' - absolutePath: %s\n' "${items[$idx]}"  printf ' - index: %s\n' "$idx"done