Module: XML

Defined in:
lib/sixarm_ruby_xml_load.rb

Class Method Summary collapse

Class Method Details

.load_attributes(dirpath, xpath) ⇒ Object

Sugar to load attributes from a file.

Examples:

XML.load_attributes('config.xml','userlist/user'){|attributes| pp attributes['first_name'] }


57
58
59
60
61
# File 'lib/sixarm_ruby_xml_load.rb', line 57

def XML.load_attributes(dirpath,xpath)
  XML.load_elements(dirpath,xpath){|elem|
    yield elem.attributes
  }
end

.load_attributes_array(dirpath, xpath) ⇒ Object

Sugar to load attributes array from a file.

Examples:

XML.load_attributes_array('config.xml','userlist/user'){|attributes| pp attributes['first_name'] }


69
70
71
72
73
# File 'lib/sixarm_ruby_xml_load.rb', line 69

def XML.load_attributes_array(dirpath,xpath)
  XML.load_elements(dirpath,xpath){|elem|
    yield elem.attributes.to_a
  }
end

.load_attributes_hash(dirpath, xpath) ⇒ Object

Sugar to load attributes hash from a file.

Examples:

XML.load_attributes_hash('config.xml','userlist/user'){|attributes| pp attributes['first_name'] }


81
82
83
84
85
# File 'lib/sixarm_ruby_xml_load.rb', line 81

def XML.load_attributes_hash(dirpath,xpath)
  XML.load_elements(dirpath,xpath){|elem|
    yield elem.attributes.to_a_hash
  }
end

.load_dir(*dirpaths) ⇒ Object

Specify one or more directory patterns and pass each XML file in the matching directories to a block.

See [Dir#glob](www.ruby-doc.org/core/classes/Dir.html#M002347) for pattern details.

Examples:

To load xml documents

XML.load_dir('/tmp/*.xml'){|xml_document|
  #...whatever you want to do with each xml document
}

To load xml documents in files beginning in “foo” or “bar”

XML.load_dir('/tmp/foo*.yaml','/tmp/bar*.xml','){|xml_document|
  #...whatever you want to do with the xml document
}


25
26
27
28
29
30
31
32
33
34
35
# File 'lib/sixarm_ruby_xml_load.rb', line 25

def XML.load_dir(*dirpaths)
  dirpaths=[*dirpaths.flatten]
  dirpaths.each do |dirpath|
    Dir[dirpath].sort.each do |filename|
      File.open(filename) do |file|
        doc = REXML::Document.new file
        yield doc
      end #file
    end #dir
  end #each
end

.load_elements(dirpath, xpath) ⇒ Object

Sugar to load elements from a file.

Examples:

XML.load_elements('config.xml','userlist/user'){|element| pp element.attributes['first_name'] }


43
44
45
46
47
48
49
# File 'lib/sixarm_ruby_xml_load.rb', line 43

def XML.load_elements(dirpath,xpath)
  XML.load_dir(dirpath){|doc|
    doc.elements.each(xpath){|elem|
      yield elem
    }
  }
end