使用shell脚本读取xml的属性值和节点值

#FUNCRION: GetNodeValue
#DESC    : Get xmlnode value
#INPUT   : 1-XmlFilePath 2-NodeName    
#OUTPUT  : nodevalue
function GetNodeValue
{  
    if [ $# -ne 2 ];then
echo "    error: arguments is not enough"
echo "    USAGE:            $0 XmlFilePath NodeName"
        echo "    XmlFilePath       xmlfile path type[${HOME}/config/datasource/bmp-xa-ds.xml]"
        echo "    NodeName          nodename type[xa-datasource-property]"
echo     e.g.:  $0 ${HOME}/config/datasource/bmp-xa-ds.xml 'xa-datasource-property name="URL"'
return
fi

CurrentTime=`date +"%Y%m%d%H%M%S"`
tmpfile="$$_$CurrentTime"
FilePath=$1
    NodeName=$2
    NodePre=`awk -v Node="$NodeName" 'BEGIN {split(Node,NodeAdd," ");print NodeAdd[1]}'`
FLAG=0
    sed 's/>/>\n/g' $FilePath | sed 's/<\//\n<\//g' | sed 's/\s*\(.*\)\s*$/\1/g' | sed '/^\(\s\)*$/d' | while read line
    do
        ISFIRST=`echo $line | sed -n "/<$NodeName/p"`
        if [ "x$ISFIRST" != "x" ]; then
            FLAG=1
        fi
        if [ ${FLAG} -eq 1 ] ; then
            echo $line >> "$tmpfile"
        fi
        ISSEC=`echo $line | sed -n "/<\/$NodePre>/"p`
        if [ "x$ISSEC" != "x" ]; then
            FLAG=0
        fi
    done
    awk '{ORS=""}{print $0}' $tmpfile | awk 'BEGIN{FS=">";RS="</"}{print $NF}' | sed '/^\(\s\)*$/d'
    rm $tmpfile
}

#FUNCRION: GetNodeAttr
#DESC    : Get xmlnode attribute
#INPUT   : 1-XmlFilePath 2-AttrName    
#OUTPUT  : node attribute
function GetNodeAttr
{  
    if [ $# -ne 2 ];then
echo "    error: arguments is not enough"
echo "    USAGE:            $0 XmlFilePath AttrName"
        echo "    XmlFilePath       xmlfile path type[${HOME}/config/DiamBaseConfig.xml]"
        echo "    AttrName          nodename type[PeerIp]"
echo "    e.g.:  $0 ${HOME}/config/DiamBaseConfig.xml PeerIp"
return
fi

FilePath=$1
    AttrName=" $2="
sed 's/>/>\n/g' $FilePath | sed 's/<\//\n<\//g' | sed 's/\s*\.*\s*$/\1/g' | sed '/^\(\s\)*$/d' | sed -n "/$AttrName/"p | sed "s/.*$AttrName\"//g" | sed 's/\".*//g'
}

你可能感兴趣的:(shell)