diff --git a/lib/nori.rb b/lib/nori.rb index ba55215..db3e51f 100644 --- a/lib/nori.rb +++ b/lib/nori.rb @@ -15,15 +15,16 @@ def self.hash_key(name, options = {}) def initialize(options = {}) defaults = { - :strip_namespaces => false, - :delete_namespace_attributes => false, - :convert_tags_to => nil, - :convert_attributes_to => nil, - :empty_tag_value => nil, - :advanced_typecasting => true, - :convert_dashes_to_underscores => true, - :scrub_xml => true, - :parser => :nokogiri + :strip_namespaces => false, + :delete_namespace_attributes => false, + :convert_tags_to => nil, + :convert_attributes_to => nil, + :empty_tag_value => nil, + :advanced_typecasting => true, + :convert_dashes_to_underscores => true, + :scrub_xml => true, + :parser => :nokogiri, + :string_with_attributes_as_hash => false, } validate_options! defaults.keys, options.keys diff --git a/lib/nori/xml_utility_node.rb b/lib/nori/xml_utility_node.rb index 63d74a4..c471025 100644 --- a/lib/nori/xml_utility_node.rb +++ b/lib/nori/xml_utility_node.rb @@ -140,8 +140,12 @@ def to_hash t = advanced_typecasting(t) if t.is_a?(String) && @options[:advanced_typecasting] if t.is_a?(String) - t = StringWithAttributes.new(t) - t.attributes = attributes + if @options[:string_with_attributes_as_hash] && attributes.any? + t = { '#text' => t }.merge(attributes.transform_keys { |k| "@#{k}" }) + else + t = StringWithAttributes.new(t) + t.attributes = attributes + end end return { name => t } diff --git a/spec/nori/nori_spec.rb b/spec/nori/nori_spec.rb index e673722..1db3ea4 100644 --- a/spec/nori/nori_spec.rb +++ b/spec/nori/nori_spec.rb @@ -231,6 +231,20 @@ expect("some-string").not_to respond_to(:attributes) expect("some-string").not_to respond_to(:attributes=) end + + it "returns hash with :string_with_attributes_as_hash option" do + xml =<<-XML + + Text + Gary R Epstein + Simon T Tyson + + XML + @data = parse(xml, { string_with_attributes_as_hash: true }) + expect(@data['opt']['test']).to eq({ '#text' => 'Text', '@attr' => 'value', '@attr1' => 'value1' }) + expect(@data['opt']['user'][0]).to eq({ '#text' => 'Gary R Epstein', '@login' => 'grep' }) + expect(@data['opt']['user'][1]).to eq('Simon T Tyson') + end end it "should typecast an integer" do