Link to home
Start Free TrialLog in
Avatar of akshay_n_s
akshay_n_s

asked on

How to parse an xml file in a shell script

XML file is in continuation, which means tags are not seperated line by lines.

I want to write a shell script which would be able to get a number within a particular tag.

E.g. OrderMgr.sh is a shell script

>sh OrderMgr.sh input.xml tagname

Output: tagname value is 10

I don't want to write a java program to do this thing...

Kindly help me regarding this....

Thanks
Akshay
Avatar of sunnycoder
sunnycoder
Flag of India image

Hi Akshay,

#!/bin/bash

value=`sed "s:.*<$2>\([^<]*\)<.*:\1:" $1`
echo "$2 value is $value"

Cheers!
sunnycoder
> I want to write a shell script which would be able to get a number within a particular tag.
you'll have a lot of difficulties doing that with shell only, I guess impossible
If you use other programs like sed, grep, awk, perl (as Tintin suggested), you have a little chance to do what you want if you're very experianced in using these tools.
XML is a strucutred format, use an XML parser, anything else is a pain even for such a simple example as you described.

perl with XML:Simple would be the simplest and quickest way to do it.
Avatar of HamdyHassan
HamdyHassan

akshay,
I already build a simple script for the same goal to help me investigate issues

$ cat a.xml
<?xml version="1.0" encoding="US-ASCII"?>
<trade>
<start_date>2006-09-01T00:00:00.000</start_date>
<end_date>2006-09-08T00:00:00.000</end_date>
<type>PR</type>
</trade>

$ search_xml.ksh a.xml type
searching a.xml for tagname type
PR

$ cat search_xml.ksh
#!/bin/ksh
echo searching $1 for tagname $2
myvalue=`grep "<$2>.*<.$2>" $1 | cut -f2 -d">"| cut -f1 -d"<"`
echo $myvalue


please let me know with any question about that script
> .. which means tags are not seperated line by lines.
HamdyHassan, did you read that?
ASKER CERTIFIED SOLUTION
Avatar of HamdyHassan
HamdyHassan

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of akshay_n_s

ASKER

Hi HamdyHassan,

Script will not work in the following case!

<Order>
       <Some>sdf</Some>
       <Tags>val</Tags>
       <ProductProfile>
            <Service>
                <Attribute Name="no_of_lines">1<\Attribute>
                <Attribute Name="no_of_lines">1<\Attribute>
           </Service>
       <ProductProfile>
       .
       .
       .
Script is not able to search --> Attribute Name="no_of_lines"
Output should be 1
   
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you very much for ur help!