module ActiveSupport::XmlMini_JDOM
def collapse(element)
element::
Actually converts an XML document element into a data structure.
def collapse(element) hash = get_attributes(element) child_nodes = element.child_nodes if child_nodes.length > 0 for i in 0...child_nodes.length child = child_nodes.item(i) merge_element!(hash, child) unless child.node_type == Node.TEXT_NODE end 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) text = '' child_nodes = element.child_nodes for i in 0...child_nodes.length item = child_nodes.item(i) if item.node_type == Node.TEXT_NODE text << item.get_data.strip end end text.strip.length == 0 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) attribute_hash = {} attributes = element.attributes for i in 0...attributes.length attribute_hash[attributes.item(i).name] = attributes.item(i).value end attribute_hash 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.has_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.tag_name, collapse(element)) end
def merge_texts!(hash, element)
element::
Hash to add the converted emement to.
hash::
Merge all the texts of an element into the hash
def merge_texts!(hash, element) text_children = texts(element) if text_children.join.empty? hash else # must use value to prevent double-escaping merge!(hash, CONTENT_KEY, text_children.join) end end
def parse(string)
string::
Parse an XML Document string into a simple hash using Java's jdom.
def parse(string) if string.blank? {} else @dbf = DocumentBuilderFactory.new_instance xml_string_reader = StringReader.new(string) xml_input_source = InputSource.new(xml_string_reader) doc = @dbf.new_document_builder.parse(xml_input_source) merge_element!({}, doc.document_element) end end
def texts(element)
element::
Determines if a document element has text content
def texts(element) texts = [] child_nodes = element.child_nodes for i in 0...child_nodes.length item = child_nodes.item(i) if item.node_type == Node.TEXT_NODE texts << item.get_data end end texts end