I have the following xml file

<root> <deviceID>IO238470374109730497</devicdeID> <KeyValuePairs> <KeyValuePair> <BASE-URL>site.com</BASE-URL> <Key>329482</Key> <Value>23094</Value> </KeyValuePair> <KeyValuePair> <BASE-URL>anothersite.com</BASE-URL> <Key>36657</Key> <Value>1233</Value> </KeyValuePair> <KeyValuePair> <BASE-URL>yetanothsite.com</BASE-URL> <Key>3345</Key> <Value>65087</Value> </KeyValuePair> </KeyValuePairs> </root>

I would like to extract the values of all <BASE-URL>,<Key>,<Value> and set them to variables in a bash script.

executing this command will only print the values

xmlstarlet sel -t -m '//KeyValuePair' -v 'concat(BASE-URL," ", Key, " ", Value, " ")' -nl file.xml

How can I set these values to variables?

I want to extract the values from the xml and send them to variables like this <BASE-URL> to $base_url , <Key> to $key and <Value> to $value.


1 Answer 1


Assuming the values never contain spaces you can do something like this:

xmlstarlet sel -t -m '//KeyValuePair' -v 'concat(BASE-URL," ", Key, " ", Value, " ")' -nl file.xml | while read base_url key value
    echo "base_url=$base_url key=$key value=$value"
  • It works.. you saved my day.. thank you very much! Commented Feb 13, 2019 at 14:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .