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.)

Share:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Slashdot
  • LinkedIn
  • Twitter
  • HackerNews
  • Suggest to Techmeme via Twitter

Related posts:

  1. Building GSL as a Universal BinaryHere's a universal binary of the Gnu Scientific library (GSL) for OS X, including the ppc, ppc64, i386 and x86_64...
  2. Installing VTK on Mac OS XDownload Universal Binaries of the VTK libraries for OS X here (also how to build them yourself). The comet program...
  3. Convert The Economist Audio Edition into an iPod audiobook with chaptersThis script re-orders The Economist Audio Edition mp3 files into an iPod audiobook, allowing you to resume from the last...
  4. Continuity of, and Diffusion through, the Endoplasmic ReticulumDiffusion through the Endoplasmic Reticulum The endoplasmic reticulum (ER) is a meshwork of narrow membrane-bound tubes running through the cytoplasm...

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