Browse > Home / Computer, How To / Blog article: Setting bash variables from an XML file

Setting bash variables from an XML file

November 8th, 2009 Posted in Computer, How To

Here's a quick way to set bash variables using data from an XML file.  Say the xml file is called 'writetext.xml' and looks like this:

<?xml version="1.0"?>
<writetext>
 <DATE>04/04/09</DATE>
 <AUTHOR>Mark</AUTHOR>
 <CROP>TRUE</CROP>
 <FONT>/Library/Fonts/Arial.ttf</FONT>
 <FONTSIZE>18</FONTSIZE>
 <FIXEDFONT>/Library/Fonts/Courier New Bold.ttf</FIXEDFONT>
 <FIXEDFONTSIZE>18</FIXEDFONTSIZE>
 <FRAMESTEP>1</FRAMESTEP>
</writetext>

...and you want to parse it for the variables 'DATE AUTHOR CROP FONT FONTSIZE FIXEDFONT FIXEDFONTSIZE FRAMESTEP', setting the corresponding bash variables to the values in the XML file.

Here's a way to do it using xmlstarlet:

VARIABLES="DATE AUTHOR CROP FONT FONTSIZE FIXEDFONT FIXEDFONTSIZE FRAMESTEP"

for VARIABLE in $VARIABLES
do
eval $VARIABLE=\"`xmlstarlet sel -t -m //writetext -v $VARIABLE writetext.xml`\"
done

Since this code snippet uses xmlstarlet to parse the XML,  you'll need to install it first using 'sudo port install xmlstarlet' on OS X or 'apt-get install xmlstarlet' on ubuntu/debian.  (You could also potentially use 'sed' to do the parsing, but I'm quite happy with xmlstarlet since regular expressions make my head hurt.)

Leave a Reply

*
To prove you're a person (not a spam script), type the security text shown in the picture. Click here to regenerate some new text.
Click to hear an audio file of the anti-spam word