ohler55 / ox

Ruby Optimized XML Parser
http://www.ohler.com/ox
MIT License
900 stars 76 forks source link

Ox.dump does not preserve xml declaration #352

Open hfabre opened 5 months ago

hfabre commented 5 months ago

Hi, i'm playing a bit with your gem to parse and update some opf file (~epub metadata file) and i found that using Ox.dump does not preserve xml declaration.

To be honest i feel like it's probably on purpose but even after reading the documention i can't find how to preserve it. It's pretty important to me because my workflow is to Ox.load my file, modifing some nodes data using Element#replace_text and finally replace the orginal file by the result of Ox.dump but of course i'm now missing the declaration line.

Any idea how i can do it ?

Thanks for your open source work !

In case this is true bug and not on purpose here is a minimal reproduction :

ox (2.14.18)

require 'ox'

xml = %{
<?xml version="1.0"?>
<Park.Animal>
  <type>mutant</type>
  <friends type="Hash">
    <i>5</i>
    <Park.Animal>
      <type>dog</type>
    </Park.Animal>
  </friends>
</Park.Animal>
}
# => "\n<?xml version=\"1.0\"?>\n<Park.Animal>\n  <type>mutant</type>\n  <friends type=\"Hash\">\n    <i>5</i>\n    <Park.Animal>\n      <type>dog</type>\n    </Park.Animal>\n  </friends>\n</Park.Animal>\n"

doc = Ox.load(xml, mode: :generic)
xml2 = Ox.dump(doc)
# => "\n<Park.Animal>\n  <type>mutant</type>\n  <friends type=\"Hash\">\n    <i>5</i>\n    <Park.Animal>\n      <type>dog</type>\n    </Park.Animal>\n  </friends>\n</Park.Animal>\n"

xml == xml2
# => false
ohler55 commented 5 months ago

Have you taken a look at the options? Try the :with_xml when dumping. xml2 = Ox.dump(doc, with_xml: true)

hfabre commented 5 months ago

It works like a charm thanks. I have looked at options but it looks like this one does not appear in the documentation

ohler55 commented 5 months ago

It is in the default_options but you are right I don't see it in the dump options. Looks like I need to regenerate the docs.