2009-03-10 23:45:14 -04:00
|
|
|
require 'nokogiri'
|
|
|
|
|
2009-03-10 15:08:42 -04:00
|
|
|
# = XmlMini Nokogiri implementation
|
2009-03-09 20:27:39 -04:00
|
|
|
module ActiveSupport
|
|
|
|
module XmlMini_Nokogiri #:nodoc:
|
|
|
|
extend self
|
|
|
|
|
2009-05-17 11:37:30 -04:00
|
|
|
# Parse an XML Document string or IO into a simple hash using libxml / nokogiri.
|
|
|
|
# data::
|
|
|
|
# XML Document string or IO to parse
|
|
|
|
def parse(data)
|
2009-06-09 10:01:50 -04:00
|
|
|
if !data.respond_to?(:read)
|
|
|
|
data = StringIO.new(data || '')
|
2009-05-17 11:37:30 -04:00
|
|
|
end
|
2009-06-09 10:01:50 -04:00
|
|
|
|
|
|
|
char = data.getc
|
|
|
|
if char.nil?
|
2009-03-10 15:08:42 -04:00
|
|
|
{}
|
|
|
|
else
|
2009-06-09 10:01:50 -04:00
|
|
|
data.ungetc(char)
|
2009-05-17 11:37:30 -04:00
|
|
|
doc = Nokogiri::XML(data)
|
2009-03-10 23:45:14 -04:00
|
|
|
raise doc.errors.first if doc.errors.length > 0
|
|
|
|
doc.to_hash
|
2009-03-10 15:08:42 -04:00
|
|
|
end
|
2009-03-09 20:27:39 -04:00
|
|
|
end
|
|
|
|
|
2009-03-21 21:44:00 -04:00
|
|
|
module Conversions #:nodoc:
|
|
|
|
module Document #:nodoc:
|
2009-03-09 20:27:39 -04:00
|
|
|
def to_hash
|
|
|
|
root.to_hash
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2009-03-21 21:44:00 -04:00
|
|
|
module Node #:nodoc:
|
2009-03-09 20:27:39 -04:00
|
|
|
CONTENT_ROOT = '__content__'
|
|
|
|
|
|
|
|
# Convert XML document to hash
|
|
|
|
#
|
|
|
|
# hash::
|
|
|
|
# Hash to merge the converted element into.
|
|
|
|
def to_hash(hash = {})
|
|
|
|
hash[name] ||= attributes_as_hash
|
|
|
|
|
2009-03-10 23:45:14 -04:00
|
|
|
walker = lambda { |memo, parent, child, callback|
|
|
|
|
next if child.blank? && 'file' != parent['type']
|
2009-03-09 20:27:39 -04:00
|
|
|
|
|
|
|
if child.text?
|
|
|
|
(memo[CONTENT_ROOT] ||= '') << child.content
|
|
|
|
next
|
|
|
|
end
|
|
|
|
|
|
|
|
name = child.name
|
|
|
|
|
2009-03-10 23:45:14 -04:00
|
|
|
child_hash = child.attributes_as_hash
|
2009-03-09 20:27:39 -04:00
|
|
|
if memo[name]
|
|
|
|
memo[name] = [memo[name]].flatten
|
2009-03-10 23:45:14 -04:00
|
|
|
memo[name] << child_hash
|
2009-03-09 20:27:39 -04:00
|
|
|
else
|
2009-03-10 23:45:14 -04:00
|
|
|
memo[name] = child_hash
|
2009-03-09 20:27:39 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
# Recusively walk children
|
2009-03-10 23:45:14 -04:00
|
|
|
child.children.each { |c|
|
|
|
|
callback.call(child_hash, child, c, callback)
|
|
|
|
}
|
2009-03-09 20:27:39 -04:00
|
|
|
}
|
|
|
|
|
2009-03-10 23:45:14 -04:00
|
|
|
children.each { |c| walker.call(hash[name], self, c, walker) }
|
2009-03-09 20:27:39 -04:00
|
|
|
hash
|
|
|
|
end
|
|
|
|
|
|
|
|
def attributes_as_hash
|
|
|
|
Hash[*(attribute_nodes.map { |node|
|
|
|
|
[node.node_name, node.value]
|
|
|
|
}.flatten)]
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
Nokogiri::XML::Document.send(:include, Conversions::Document)
|
|
|
|
Nokogiri::XML::Node.send(:include, Conversions::Node)
|
|
|
|
end
|
|
|
|
end
|