Search code examples
rubyxmlkmllibxml2libxml-ruby

Add raw XML into XML document built with libxml-ruby


Working with KMLs (which of course are XML), I have loads of styles which – for humans – are easiest to read and maintain as raw XML. I'd like to add those into a XML document being built with libxml-ruby.

Here's a simplified example:

require 'xml'

raw_xml = <<~END
  <Style>
    <foo>bar</foo>
  </Style>
END

xml = XML::Document.new
xml.root = XML::Node.new(:Document)
xml.root << raw_xml
xml.to_s

The result:

<?xml version="1.0" encoding="UTF-8"?>
<Document>&lt;Style&gt;
  &lt;foo&gt;bar&lt;/foo&gt;
&lt;/Style&gt;
</Document>

That was to be expected since << does not parse the raw XML. My question, however, is there a way to do this right and get the the following output?

<?xml version="1.0" encoding="UTF-8"?>
<Document>
  <Style>
    <foo>bar</foo>
  </Style>
</Document>

Thanks for your hints!


Solution

  • xml.root is an instance of LibXML::XML::Node, its << ,method is for adding a node. Not for parsing XML string.

    To parse a string, you can use for example XML::Parser.string:

    xml = XML::Document.new
    xml.root = XML::Node.new(:Document)
    # Parse the string into XML::Document, then take its root node tree
    another_doc = XML::Parser.string(raw_xml).parse
    node = xml.import(another_doc.root)
    xml.root << node