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
|
|
|
|
|
|
|
|
# Parse an XML Document string into a simple hash using libxml / nokogiri.
|
|
|
|
# string::
|
|
|
|
# XML Document string to parse
|
|
|
|
def parse(string)
|
2009-03-10 15:08:42 -04:00
|
|
|
if string.blank?
|
|
|
|
{}
|
|
|
|
else
|
2009-03-10 23:45:14 -04:00
|
|
|
doc = Nokogiri::XML(string)
|
|
|
|
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
|