Parse XML

Hi all!

I'm looking to write a quick script and in it I need to request an XML file from a service running on localhost and parse that XML file and output it. I'm looking to do it in bash although it doesn't really matter what shell it is in. The XML file returned would look like this:

<?xml version="1.0" encoding="UTF-8" ?> 
<queue> 
    <paused>True</paused> 
    <kbpersec>0.0</kbpersec> 
    <mbleft>854.697840691</mbleft> 
    <mb>854.697840691</mb> 
    <noofslots>1</noofslots> 
    <diskspace1>21.980682373</diskspace1> 
    <diskspace2>21.980682373</diskspace2> 
    <timeleft>0:00:00</timeleft>     
    <jobs>
        <job> 
        <id>SABnzbd_nzo_zt2syz</id> 
        <msgid>3066202</msgid> 
        <filename>Ubuntu 8.04 (Hardy Heron) - Desktop CD x64</filename> 
        <mbleft>854.697840691</mbleft> 
        <mb>854.697840691</mb> 
        <index>0</index> 
        <unpackopts>3</unpackopts> 
        <cat>Apps</cat> 
        <script>snarl.exe</script> 
        <status>Queued</status> 
        <percentage>0</percentage> 
        <bytes>896215643.0</bytes> 
        </job>
    </jobs>
</queue>

Any help getting the XML parsed would be great! Thanks in advance!

You'd better use an XML parser, shell is not good at it.

Thanks. I just realized that shell probably isn't going to be very powerful for this. Looks like Perl would be a better option. Anyone have any examples that would work with my XML example?

it depends on what language you are comfortable with. I like ruby , so here's a ruby example

  #!/usr/bin/env ruby  -Ku 
require 'rexml/document' 
include REXML 
File.open("file") do |doc| 
  xml = Document.new(doc) 
  xml.elements.each("queue") do |elem| 
    elem.elements.each {|x| print "->#{x}\n" } 
  end 
end 
 

of course, other languages like Perl/Python etc have XML libraries as well. Read their documentation for usage.