[linux] Re: bash en xml

Wybo Dekker wybo op servalys.nl
Do mei 4 22:28:58 CEST 2006


On Thu, 4 May 2006, Koen de Jonge (ProcoliX) wrote:

> Cecil Westerhof wrote:
>>>> Weet iemand of er een eenvoudige manier is om met bash informatie
>>>> uit
>>>> XML bestanden te halen?

> Voor zoiets zou ik nou typisch perl gebruiken met eventueel een module of 2.

of kijk eens naar Ruby. Hier is een demo-scriptje:

-----------------------------------------------------------
#!/usr/local/bin/ruby

require 'rexml/document'
include REXML


# read and process the XML data in the DATA section:
xml = REXML::Document.new(DATA)

puts "Root element: #{xml.root.name}"
puts "\nThe names of all classes:"
xml.elements.each("//class") {|c| puts "\t" + c.attributes["name"] }
puts "\nThe description of Fixnum:"
puts xml.elements["//class[@name='Fixnum']"].text

# Sample code from Programing Ruby, page 726

cls = Element.new("class")
cls.attributes["name"] = "Rational"
cls.text = "Represents complex numbers"

puts "\nRemove Integer's children, and add"
puts "our new node as the one after Integer,"

int = xml.elements["//class[@name='Integer']"]

int.delete_at(1)
int.delete_at(2)

int.next_sibling = cls

puts "change all the 'name' attributes to class_name,"

xml.elements.each("//class") do |c|
   c.attributes['class_name'] = c.attributes['name']
   c.attributes.delete('name')
end

puts "and write it out with a XML declaration at the front:"
puts

xml << XMLDecl.new
xml.write(STDOUT, 0)


__END__
<classes language="ruby">
   <class name="Numeric">
     Numeric represents all numbers.
     <class name="Float">
       Floating point numbers have a fraction and a mantissa.
     </class>
     <class name="Integer">
       Integers contain exact integral values.
       <class name="Fixnum">
         Fixnums are stored as machine ints.
       </class>
       <class name="Bignum">
         Bignums store arbitraty-sized integers.
       </class>
     </class>
   </class>
</classes>
----------------------------------
met als uitvoer:

Root element: classes

The names of all classes:
         Numeric
         Float
         Integer
         Fixnum
         Bignum

The description of Fixnum:

         Fixnums are stored as machine ints.


Remove Integer's children, and add
our new node as the one after Integer,
change all the 'name' attributes to class_name,
and write it out with a XML declaration at the front:

<?xml version='1.0'?>
<classes language='ruby'>
   <class class_name='Numeric'>
     Numeric represents all numbers.
     <class class_name='Float'>
       Floating point numbers have a fraction and a mantissa.
     </class>
     <class class_name='Integer'>
       Integers contain exact integral values.


     </class>
     <class class_name='Rational'>Represents complex 
numbers</class>
   </class>
</classes>



-- 
Wybo



More information about the Linux mailing list