How can I get the value from an attribute using xmllint and XPath?
You need to use fn:string(), which will return the value of its argument as xs:string
. In case its argument is an attribute, it will therefore return the attribute's value as xs:string
.
test=$(xmllint --xpath "string(//body/value/@name)" test.xml)
An approach with a helper awk
command that supports multiple attributes (a streamlined version of ego's approach):
echo 'cat //*/@name' | xmllint --shell file | awk -F\" 'NR % 2 == 0 { print $2 }'
The awk
command:
splits
xmllint
's output lines into fields by"
chars. (-F\"
)- Note that
xmllint
normalizes quoting around attribute values to"..."
on output, even if the input had'...'
, so it's sufficient to split by"
.
- Note that
only processes even-numbered lines (
NR %2 == 0
), thereby filtering out the separator lines thatcat
invariably prints.print $2
then prints only the 2nd field, which is the value of each attribute without the enclosing"..."
.
Assuming the following sample XML in file
:
<body> <value name="abc"></value> <value name="def"></value></body>
the above yields:
abcdef