3 # = XmlMini LibXML implementation
5 module XmlMini_LibXML
#:nodoc:
8 # Parse an XML Document string into a simple hash using libxml.
10 # XML Document string to parse
12 LibXML
::XML.default_keep_blanks
= false
17 LibXML
::XML::Parser.string(string
.strip
).parse
.to_hash
33 CONTENT_ROOT
= '__content__'
34 LIB_XML_LIMIT
= 30000000 # Hardcoded LibXML limit
36 # Convert XML document to hash
39 # Hash to merge the converted element into.
42 raise LibXML
::XML::Error if content
.length
>= LIB_XML_LIMIT
43 hash
[CONTENT_ROOT
] = content
45 sub_hash
= insert_name_into_hash(hash
, name
)
46 attributes_to_hash(sub_hash
)
48 children_array_to_hash(sub_hash
)
50 children_yaml_to_hash(sub_hash
)
52 children_to_hash(sub_hash
)
60 # Insert name into hash
63 # Hash to merge the converted element into.
65 # name to to merge into hash
66 def insert_name_into_hash(hash
, name
)
69 if !hash
[name
].kind_of
? Array
70 hash
[name
] = [hash
[name
]]
72 hash
[name
] << sub_hash
79 # Insert children into hash
82 # Hash to merge the children into.
83 def children_to_hash(hash
={})
84 each
{ |child
| child
.to_hash(hash
) }
85 attributes_to_hash(hash
)
89 # Convert xml attributes to hash
92 # Hash to merge the attributes into
93 def attributes_to_hash(hash
={})
94 each_attr
{ |attr
| hash
[attr
.name
] = attr
.value
}
98 # Convert array into hash
101 # Hash to merge the array into
102 def children_array_to_hash(hash
={})
103 hash
[child
.name
] = map
do |child
|
104 returning({}) { |sub_hash
| child
.children_to_hash(sub_hash
) }
109 # Convert yaml into hash
112 # Hash to merge the yaml into
113 def children_yaml_to_hash(hash
= {})
114 hash
[CONTENT_ROOT
] = content
unless content
.blank
?
118 # Check if child is of type array
120 child
? && child
.next? && child
.name
== child
.next.name
123 # Check if child is of type yaml
125 attributes
.collect
{|x
| x
.value
}.include?('yaml')
132 LibXML
::XML::Document.send(:include, LibXML
::Conversions::Document)
133 LibXML
::XML::Node.send(:include, LibXML
::Conversions::Node)