简体   繁体   中英

Bash script parse xml elements to key=value pairs with XMLStarlet

I have this xml file (filename: myFile.xml) with user's data:

<?xml version="1.0" encoding="utf-8"?>
<params>
    <username>jDoe</username>
    <password>abc123</password>
    <firstname>John</firstname>
    <lastname>Doe</lastname>
    <email>jdoe@example.com</email>
    <country>Germany</country>
</params>

I can open it in my bash script and use a "for" loop to iterate it's contents:

for i in $(xmlstarlet select -t -v '/params/*' myFile.xml)
do
   echo $i
done

When I run it I get:

jDoe
abc123
John
Doe
jdoe@example.com
Germany

How can I associate each value with it's relative name, and create a bash script variable like this:

username="jDoe"
password="abc123"
firstname="John"
lastname="Doe"
email="jdoe@example.com"
country="Germany"

In other words, for each tag I want to read it's name and it's value, and then create a bash variable out of that. ie:

tagname="value"

I prefer to loop through the tags because they are a lot more than this example and not always the same.

Any suggestions?

xmlstarlet select --template --match "//params/*" --value-of "concat(name(),'=\"',text(),'\"')" -n file.xml

Output:

username="jDoe"
password="abc123"
firstname="John"
lastname="Doe"
email="jdoe@example.com"
country="Germany"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM