Easy API to maintain XML (especially configuration files).
Define some reasonable defaults.
Declare options that are valid for xml_in and xml_out.
Creates and intializes a new XmlSimple object.
defaults |
Default values for options. |
# File lib/xmlsimple.rb, line 128 def initialize(defaults = nil) unless defaults.nil? || defaults.is_a?(Hash) raise ArgumentError, "Options have to be a Hash." end @default_options = normalize_option_names(defaults, (KNOWN_OPTIONS['in'] + KNOWN_OPTIONS['out']).uniq) @options = Hash.new @_var_values = nil end
Converts an XML document in the same way as the Perl module XML::Simple.
string |
XML source. Could be one of the following:
|
options |
Options to be used. |
# File lib/xmlsimple.rb, line 149 def xml_in(string = nil, options = nil) handle_options('in', options) # If no XML string or filename was supplied look for scriptname.xml. if string.nil? string = File::basename($0).dup string.sub!(/\.[^.]+$/, '') string += '.xml' directory = File::dirname($0) @options['searchpath'].unshift(directory) unless directory.nil? end if string.is_a?(String) if string =~ /<.*?>/ @doc = parse(string) elsif string == '-' @doc = parse($stdin.read) else filename = find_xml_file(string, @options['searchpath']) if @options.has_key?('cache') @options['cache'].each { |scheme| case(scheme) when 'storable' content = @@cache.restore_storable(filename) when 'mem_share' content = @@cache.restore_mem_share(filename) when 'mem_copy' content = @@cache.restore_mem_copy(filename) else raise ArgumentError, "Unsupported caching scheme: <#{scheme}>." end return content if content } end @doc = load_xml_file(filename) end elsif string.respond_to?(:read) @doc = parse(string.read) else raise ArgumentError, "Could not parse object of type: <#{string.class}>." end result = collapse(@doc.root) result = @options['keeproot'] ? merge({}, @doc.root.name, result) : result put_into_cache(result, filename) result end
Converts a data structure into an XML document.
ref |
Reference to data structure to be converted into XML. |
options |
Options to be used. |
# File lib/xmlsimple.rb, line 212 def xml_out(ref, options = nil) handle_options('out', options) if ref.is_a?(Array) ref = { @options['anonymoustag'] => ref } end if @options['keeproot'] keys = ref.keys if keys.size == 1 ref = ref[keys[0]] @options['rootname'] = keys[0] end elsif @options['rootname'] == '' if ref.is_a?(Hash) refsave = ref ref = {} refsave.each { |key, value| if !scalar(value) ref[key] = value else ref[key] = [ value.to_s ] end } end end @ancestors = [] xml = value_to_xml(ref, @options['rootname'], '') @ancestors = nil if @options['xmldeclaration'] xml = @options['xmldeclaration'] + "\n" + xml end if @options.has_key?('outputfile') if @options['outputfile'].kind_of?(IO) return @options['outputfile'].write(xml) else File.open(@options['outputfile'], "w") { |file| file.write(xml) } end end xml end
Generated with the Darkfish Rdoc Generator 2.