kgiszczak / shale

Shale is a Ruby object mapper and serializer for JSON, YAML, TOML, CSV and XML. It allows you to parse JSON, YAML, TOML, CSV and XML data and convert it into Ruby data structures, as well as serialize data structures into JSON, YAML, TOML, CSV or XML.
https://shalerb.org/
MIT License
618 stars 19 forks source link

Ox adapter XML to object mapper not working with xml header specified #30

Closed tomkra closed 7 months ago

tomkra commented 7 months ago

Example XML:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<PACKAGE>
  <version>2</version>
  <empty_offers>1</empty_offers>
  <definictions>definictions.xml</definictions>
  <FILES>
    <file>13467_20230926_100629_001.xml</file>
  </FILES>
</PACKAGE>

Shale mapper:

require 'shale/adapter/ox'
Shale.xml_adapter = Shale::Adapter::Ox

module Asari::XmlParser
  class Cfg < Shale::Mapper
    attribute :version, Shale::Type::Integer
    attribute :empty_offers, Shale::Type::Integer
    attribute :definictions, Shale::Type::String

    xml do
      map_element 'version', to: :version
      map_element 'empty_offers', to: :empty_offers
      map_element 'definictions', to: :definictions
    end
  end
end

When the XML header <?xml version="1.0" encoding="utf-8" standalone="yes"?> is included in XML file, attributes are not mapped correctly:

# with XML header included
Asari::XmlParser::Cfg.from_xml(xml))
=> #<Asari::XmlParser::Cfg:0x00007f82971aa038 @version=nil, @empty_offers=nil, @definictions=nil>

# without XML header included
Asari::XmlParser::Cfg.from_xml(xml))
=> #<Asari::XmlParser::Cfg:0x00007f8299c22d10 @version=2, @empty_offers=1, @definictions="definictions.xml">

When I try for example Nokogiri adapter, everything works as expected with or without XML header. I've tried to specify root element, but It's not working either.

Am I doing something wrong? All examples are without XML header tag, but It's possible to generate XML document with XML header included, so I think It should work.

kgiszczak commented 7 months ago

Thanks for pointing it out. The fix is ready on master.

tomkra commented 7 months ago

Thank you :)