3

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>[email protected]</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 [email protected] 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="[email protected]" 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?

    1 Answer 1

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

    Output:

     username="jDoe" password="abc123" firstname="John" lastname="Doe" email="[email protected]" country="Germany" 
    2
    • What does the -n before the file name?
      – dawg
      CommentedApr 27, 2021 at 13:17
    • @dawg: -n adds a new line after every key-value-pair.
      – Cyrus
      CommentedApr 27, 2021 at 16:44

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.