You are not logged in.

#1 2008-03-12 18:56:48

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

How to syndicate XML in a shell script? [SOLVED]

I am trying to write a script which will read http://www.weather.gov/data/current_obs/KLEX.xml and extract the temperature (<temp_c>), pressure (<pressure_mb>), and humidity (<relative_humidity>). Can anyone help me? I suspect I need to use wget...

#!/bin/bash

case "$1" in

t) echo "12 °C" ;;
p) echo "1014.7 mb" ;;
h) echo "51%" ;;

esac

Last edited by tony5429 (2008-03-13 01:29:09)

Offline

#2 2008-03-12 21:31:07

Zepp
Member
From: Ontario, Canada
Registered: 2006-03-25
Posts: 334
Website

Re: How to syndicate XML in a shell script? [SOLVED]

#!/bin/sh

cd /tmp

wget -nc http://www.weather.gov/data/current_obs/KLEX.xml 2> /dev/null

grep -e "<temp_c>" -e "<pressure_mb>" -e "<relative_humidity>" KLEX.xml | \
 sed 's/^[ \t]*//' | sed -e 's/<[^>]*>//g'

rm -f KLEX.xml

The only problem is if the values change order you will have no idea which line corresponds to which value. You could run 3 grep/sed instances matching each one individually though if you want. Or you can use something fancier but I'd need to know how you intend to use these values.

Edit: There are a few other safety checks I ignored, like did wget succeed, but you can add that in easily if you feel like it.

Last edited by Zepp (2008-03-12 21:41:58)

Offline

#3 2008-03-12 23:59:53

ibendiben
Member
Registered: 2007-10-10
Posts: 519

Re: How to syndicate XML in a shell script? [SOLVED]

In this cases I find it useful to store the xml variables in bash variable so you can use them any way you want later on.
It is quite easy to change the xml format in a bash script that stores all information in variables according to their names and values, what you could do for example is:

wget -nc http://www.weather.gov/data/current_obs/KLEX.xml
sed -n 's#^.*<\(.*\)>\(.*\)</.*>$#\1="\2"#p' KLEX.xml >/tmp/test
source /tmp/test
echo "Temperature: $temp_c
Pressure: $pressure_mb
Humidity: $relative_humidity"

Succes! wink

Offline

#4 2008-03-13 01:28:49

tony5429
Member
Registered: 2006-03-28
Posts: 1,017

Re: How to syndicate XML in a shell script? [SOLVED]

Thanks! It works!

Offline

Board footer

Powered by FluxBB