module MultiXml::Parsers::Rexml
def collapse(element)
element::
Actually converts an XML document element into a data structure.
def collapse(element) hash = get_attributes(element) if element.has_elements? element.each_element { |child| merge_element!(hash, child) } merge_texts!(hash, element) unless empty_content?(element) hash else merge_texts!(hash, element) end end
def empty_content?(element)
element::
Determines if a document element has text content
def empty_content?(element) element.texts.join.strip.empty? end
def get_attributes(element)
element::
Returns an empty Hash if node has no attributes.
Converts the attributes array of an XML element into a hash.
def get_attributes(element) attributes = {} element.attributes.each { |n, v| attributes[n] = v } attributes end
def merge!(hash, key, value)
value::
Key to be added.
key::
Hash to add key/value pair to.
hash::
appended to that Array.
an Array, it will be wrapped in an Array. Then the new value is
already exists and the existing value associated with key is not
Adds a new key/value pair to an existing Hash. If the key to be added
def merge!(hash, key, value) if hash.key?(key) if hash[key].instance_of?(Array) hash[key] << value else hash[key] = [hash[key], value] end elsif value.instance_of?(Array) hash[key] = [value] else hash[key] = value end hash end
def merge_element!(hash, element)
element::
Hash to merge the converted element into.
hash::
Convert an XML element and merge into the hash
def merge_element!(hash, element) merge!(hash, element.name, collapse(element)) end
def merge_texts!(hash, element)
element::
Hash to add the converted element to.
hash::
Merge all the texts of an element into the hash
def merge_texts!(hash, element) if element.has_text? # must use value to prevent double-escaping texts = element.texts.map(&:value).join merge!(hash, MultiXml::CONTENT_ROOT, texts) else hash end end
def parse(xml)
xml::
Parse an XML Document IO into a simple hash using REXML
def parse(xml) doc = REXML::Document.new(xml) raise(REXML::ParseException, "The document #{doc.to_s.inspect} does not have a valid root") unless doc.root merge_element!({}, doc.root) end
def parse_error
def parse_error ::REXML::ParseException end