How to Parse Xml Using Shellscript

How to parse XML using shellscript?

You could try xmllint

The xmllint program parses one or more
XML files, specified on the command
line as xmlfile. It prints various
types of output, depending upon the
options selected. It is useful for
detecting errors both in XML code and
in the XML parser itse

It allows you select elements in the XML doc by xpath, using the --pattern option.

On Mac OS X (Yosemite), it is installed by default.

On Ubuntu, if it is not already installed, you can run apt-get install libxml2-utils

How to extract XML data in shell script?

This answer may help
How to parse XML using shellscript?

Easier way is, if you know exactly what tag you want you can do

rg -o '<members>(.*)</members>' -r '$1' < your.xml

rg is ripgrep (https://github.com/BurntSushi/ripgrep), a great tool but you need to install

How to parse an xml and get value using shell script

You can use this xmlstarlet command to extract the values:

xmlstarlet sel -t \
-v '//module-option[@name = "userName"]/@value' \
-nl \
-v '//module-option[@name = "password"]/@value' \
file.xml

and, assuming your shell is bash, to read those values into shell variables, use a Process Substitution:

{
IFS= read -r userName
IFS= read -r password
} < <(
xmlstarlet sel -t -v '//module-option[@name = "userName"]/@value' -nl -v '//module-option[@name = "password"]/@value' file.xml
)

echo "$userName"; echo "$password"
admin
YSFSDwe

Extract an XML element value in shell script

For parsing xml files use xml parsers.

xmllint --xpath 'string(//version)' -

Shell script, parse XML snippet

You can use xmlstarlet to get the attr:

$ xmlstarlet sel -t -m //objects -v @retrieved input.xml
0

Or

$ xmlstarlet sel -t -m //objects/@retrieved -v . input.xml

-m or --match <xpath>     - match XPATH expression
-v or --value-of <xpath> - print value of XPATH expression

How to read XML and write to text file using shell script?

Try following and let me know if this helps you.

awk '
/<\/Data>/{
a="";
next
}
/<Data>/{
a=1;
next
}
/location/ && a{
gsub(/\"|>/,"",$NF);
location=$NF;
next
}
/Name/ && a{
name=$2;
next
}
/ID/ && a{
print "Name : ",name RS "ID: ",$2 RS "Location: ",location;
next
}
' Input_file

As per OP's request sine NO TAGS should be hard coded so adding following solution too now.

EDIT2: I am not a xml expert but tried it here, could you please check once.

awk 'NF==1 && (/ +<[a-zA-Z]+>/ || /^<[a-zA-Z]+>/ || / +<\/[a-zA-Z]+>/){
next
}
{
sub(/^ +/,"")
gsub(/\"|<|>/,"",$0);
sub(/\/.*/,"");
if($0){
print
}
}
' Input_file


Related Topics



Leave a reply



Submit