Get value from .XML file in Linux

Posted on

Problem :

  • Anyone got a nice solution for this:

  • I want the value: /PlayDirList/PlayDir.1378803204 from this XML.

        <setting id="ask_set_logo_to_bg" value="false" />
        <setting id="check_update_interval" value="0" />
        <setting id="clientid" value="DMDS-MVG-0001" />
        <setting id="guinotify" value="false" />
        <setting id="pil_is_broken" value="false" />
        <setting id="playdir" value="/PlayDirList/PlayDir.1378803204" />
        <setting id="runonstartup" value="true" />
        <setting id="schedule_poweroff" value="false" />
        <setting id="schedule_poweroff1" value="false" />
        <setting id="schedule_poweroff2" value="false" />
        <setting id="schedule_poweroff_custom" value="false" />
        <setting id="schedule_poweroff_from_day0" value="1" />
        <setting id="schedule_poweroff_from_day1" value="5" />
        <setting id="schedule_poweroff_from_day2" value="5" />
        <setting id="schedule_poweroff_hour0" value="23" />
        <setting id="schedule_poweroff_hour1" value="23" />
        <setting id="schedule_poweroff_hour2" value="23" />
        <setting id="schedule_poweroff_min0" value="0" />
        <setting id="schedule_poweroff_min1" value="0" />
        <setting id="schedule_poweroff_min2" value="0" />
        <setting id="schedule_poweroff_to_day0" value="0" />
        <setting id="schedule_poweroff_to_day1" value="6" />
        <setting id="schedule_poweroff_to_day2" value="0" />
        <setting id="stat_report_interval" value="600" />
        <setting id="sync_screenshot" value="true" />
        <setting id="use_external_downloader" value="true" />
        <setting id="boot_time" value="2013-10-07 09:29:23" />
  • Its a Linux box and I prefer not to install any additional application to get it done. So a nice perl, python or bash solution is prefered.

Solution :

You can use xmllint and XPATH for that:

xmllint --xpath //setting[id='playdir']/@value xmlfilename.xml

or if you are using python,

import libxml2

doc = libxml2.parseFile('foo.xml')
for setting in doc.xpathEval('//setting[id="playdir"]'):
  print setting.prop('value')
gawk '/id="playdir"/{match($0,/value="[^"]*/); print substr($0, RSTART+7,RLENGTH-7)}'