Skip to main content

How to read attributes of a XML tag using easy shell script - Part 2

If you've seen "How to read attributes of a XML tag using easy shell script - Part1", then we can see another type of XML parsing using basic shell scripts.


Lets consider another type of XML file where the value of attributes are enclosed with XML tags. Below is the sample XML:

<Fix>
    <FixType>Hot Fix</FixType>
    <FixName>shellShock.pkg</FixName>
    <FixVersion>HF0018</FixVersion>
    <FixID>22650018</FixID>
</Fix>

If we want to read all the values of the attributes, then we will have to read line by line and then separate the entity and content, else if were only interested in a particular entity, say "FixVersion" (aka entity) and its content which is "HF0018".

The below script will read each line of an XML and then take necessary action:


#!/bin/sh

read_dom () {
    local IFS=\>
    read -d \< ENTITY CONTENT
}

#specify the file or pass it as an argument to the script

file=/etc/policies/demo.xml
while read_dom; do
    case $ENTITY in
        "FixName")
                echo "$ENTITY=$CONTENT"
               #some code to process this data
               ;;
               
        "FixVersion")
                echo "$ENTITY=$CONTENT"
                #some code to process this data
                ;;

        "FixID")
                echo "$ENTITY=$CONTENT"
                #some code to process this data
    esac
done < $file


Output (echo statements):
FixName=shellShock.pkg
FixVersion=HF0018
FixID=22650018