Home > Operating Systems, Shell Scripting > Reading XML file using shell script

Reading XML file using shell script

This was like the first time where I had to write something that will be able to read something out of a XML file using a shell script. Usually I would use Python/Perl as my favorite choices in such a scenario but in this one I really *had* to do all within a shell script.

This is an example of the type of XML file I had to read:

<changelog>Fixed a new bug</changelog>
<name>Shoaib Mir</name>
<date>Sun, 02 May 2010</date>

I ended up having a shell script like this:


#Looking for four keywords in here
for key in changelog name date email
OUTPT=`grep $key log.xml | tr -d '\t' | sed 's/^\([^<].*\)$/\1/' `
eval ${key}=`echo -ne \""${OUTPT}"\"`

# Getting the results in four specific arrays
changelogarr=( `echo ${changelog}` )
namearr=( `echo ${name}` )
datearr=( `echo ${date}` )
emailarr=( `echo ${email}` )

#Print all Arrays
echo ${changelogarr[@]}
echo ${namearr[@]}
echo ${datearr[@]}
echo ${emailarr[@]}

Which gives me an output:

shoaib@shoaib-desktop:~/Desktop$ ./readxml.sh
Fixed a new bug Shoaib Mir
Sun, 02 May 2010

Shoaib Mir

  1. Anu
    October 11, 2011 at 11:53 pm

    hi, here is a scenario, where one xml tag contain more values, how do you fetch that value??


    Now I have to get number=”123″, please let me know how to achieve this?

  2. Alan Santos
    February 9, 2012 at 4:35 am

    Thank you man!

    That’s great work!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: