parsing xml using awk

hello ,

i am trying to parse xml using awk however its a little bit tricky as i want

<databases>
                <source>
                        <host>prod</host>
                        <port>1522</port>
                        <tns>GP1</tns>
                        <user>P11</user>
                        <password>lXXXXX</password>
                </source>
                <target>
                        <host>bcp</host>
                        <port>1522</port>
                        <tns>PDG</tns>
                        <user>pg</user>
                        <password>yyyyy</password>
                </target>
        </databases>

i would like to get two strings from soource and target
sqlplus p11/XXXXXX@GP1
sqlplus pg/yyyyy@pdg

any advices ?

Well, the trick is to use either the ">" or the "<" as your record separator.

 awk -v RS="<" {print} <<+ |\
 awk -F ">" '$1 ~ /^tns$/{TNS=$2}
             $1 ~ /^user$/{USER=$2}
             $1 ~ /^password$/{PW=$2}
             $1 ~ /^\/source$/{print TNS, USER, PW}'
<databases>
                <source>
                        <host>prod</host>
                        <port>1522</port>
                        <tns>GP1</tns>
                        <user>P11</user>
                        <password>lXXXXX</password>
                </source>
+

returns


GP1 P11 lXXXXX

The rest if formating the output - over to you.

Base on OP data sample:

awk -F'[<|>]' '/tns/{t=$3}/user/{u=$3}/password/{printf "sqlplus %s/%s@%s\n",t,$3,u}' file
nawk 'BEGIN{FS="[<|>]"}
/<tns>/{tns=$3}
/<user>/{user=$3}
/<password>/{printf("sqlplus %s/%s@%s\n",user,$3,tns)}' a.txt

Hi danmero

Could you please explain your command details, how it works..
i did not exactly the meaning..

Thanks
Sha

Works fine !! Many thanks...such a simple code :slight_smile:

# awk -F'[<|>]' '                              # Set the field separator to < or >
/tns/        {                                 # If line contain word "tsn" 
                 t=$3                          # Assign the value of third field to variable n
               }
/user/       {                                 # If line contain word "user" 
                 u=$3                          # Assign the value of third field to variable u
               }
/password/{                                    # If line contain word "password"
                 printf \                      # I use printf to print the line
                 "sqlplus %s/%s@%s\n",\        # Format the print output
                 t,$3,u                        # Print variable t, value of $3 and variable u
               }
' file                                         # Input file

Next time you should ask the OP :wink: