Search code examples
xmlbashxpathxmllint

bash script to read & store xml value


I have an xml file I would like to retrieve the filePath value and store it as a variable to use to launch an app. Here's the xml file:

<?xml version="1.0"?>
<resultset statement="SELECT * FROM dms.gamThr_exp
" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <row>
    <field name="id">1</field>
    <field name="filePath">/home/drs/Videos/Game.of.Thrones/Game.of.Thrones.S01E01.mkv</field>
 </row>
</resultset>

I have pieced this script together but its not working:

#!/bin/bash
myvar=$(echo 'cat //row/field[@name="filePath"]/@value' | xmllint --shell /home/drs/dms/gamThr.xml | awk -F'[="]' '{print $(NF-1)}') 
vlc --fullscreen "$myvar"

any help getting this to work will be greatly appreciated!


Solution

  • To select the text node of the context node, use the text() node test:

    //row/field[@name="filePath"]/text()
    

    Use the --xpath option of xmllint to pass the xpath:

    xmllint --xpath '//row/field[@name="filePath"]/text()' /home/drs/dms/gamThr.xml
    

    Finally your script should look like:

    #!/bin/bash
    
    myvar=$(xmllint --xpath '//row/field[@name="filePath"]/text()' /home/drs/dms/gamThr.xml) 
    vlc --fullscreen "$myvar"