Nori
Really simple XML parsing ripped from Crack, which ripped it from Merb.
Nori supports pluggable parsers and ships with both REXML and Nokogiri implementations.
It defaults to Nokogiri since v2.0.0, but you can change it to use REXML via:
Nori.new(:parser => :rexml)
Make sure Nokogiri is in your LOAD_PATH when parsing XML, because Nori tries to load it when it's needed.
Examples
Nori.new.parse("<tag>This is the content</tag>")
Nori.new.parse('<foo />')
Nori.new.parse('<foo bar />')
Nori.new.parse('<foo bar="baz"/>')
Nori.new.parse('<foo bar="baz">Content</foo>')
Nori::StringWithAttributes
You can access a string node's attributes via attributes
.
result = Nori.new.parse('<foo bar="baz">Content</foo>')
result["foo"].class
result["foo"].attributes
advanced_typecasting
Nori can automatically convert string values to TrueClass
, FalseClass
, Time
, Date
, and DateTime
:
Nori.new.parse("<value>true</value>")
Nori.new.parse("<value>09:33:55.7Z</value>")
Nori.new(advanced_typecasting: false).parse("<value>true</value>")
strip_namespaces
Nori can strip the namespaces from your XML tags. This feature is disabled by default.
Nori.new.parse('<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"></soap:Envelope>')
Nori.new(:strip_namespaces => true).parse('<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"></soap:Envelope>')
convert_tags_to
Nori lets you specify a custom formula to convert XML tags to Hash keys using convert_tags_to
.
Nori.new.parse('<userResponse><accountStatus>active</accountStatus></userResponse>')
parser = Nori.new(:convert_tags_to => lambda { |tag| Nori::StringUtils.snakecase(tag).to_sym })
parser.parse('<userResponse><accountStatus>active</accountStatus></userResponse>')
convert_dashes_to_underscores
By default, Nori will automatically convert dashes in tag names to underscores.
Nori.new.parse('<any-tag>foo bar</any-tag>')
parser = Nori.new(:convert_dashes_to_underscores => false)
parser.parse('<any-tag>foo bar</any-tag>')