Setting bash variables from an XML file
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.)