Home > OS >  Parse XML with multiple attribute in bash using xmllint
Parse XML with multiple attribute in bash using xmllint

Time:04-14

I am new in XML parsing in bash and I wanted to parse the xml below to get the values of ident, host and username attributes.

<config>
   <connectionstring>
         <ftpconfig ident="testftp" host="ftphost" username="456def" password="abc123" localdir="/local/dir/test" />
   </connectionstring>
</config>

So far, I can get the value of single attribute using xmllint. But, this is what I wanted to achieve.

1st. Get the host value using ident attribute. --> I achieve it using this.

hostv=$(echo 'cat /config/connectionstring/ftpconfig[@ident="testftp"]/@host' | xmllint --shell myxml.xml | awk -F\" '/=/ { print $2; }')

2nd. Get the username value using ident and host attribute --> this is where I am stuck. I tried different approaches like below.

userv=$(echo 'cat /config/connectionstring/ftpconfig[@ident="testftp"]/@host=\""$hostv"\"/@username' | xmllint --shell myxml.xml | awk -F\" '/=/ { print $2; }')

Thanks in advance for your help.

CodePudding user response:

What about this?

xmllint --xpath '/config/connectionstring/ftpconfig[@ident="testftp" and @host="ftphost"]/@username' myxml.xml
 username="456def"

And to get only the value of the username attribute you can use string():

xmllint --xpath 'string(/config/connectionstring/ftpconfig[@ident="testftp" and @host="ftphost"]/@username)' file.xml
456def
  • Related