ruby - Nokogiri and XML Formatting When Inserting Tags -
i'd use nokogiri insert nodes xml document. nokogiri uses nokogiri::xml::builder
class insert or create new xml.
if create xml using new
method, i'm able create nice, formatted xml:
builder = nokogiri::xml::builder.new |xml| xml.product { xml.test "hi" } end puts builder
outputs following:
<?xml version="1.0"?> <product> <test>hi</test> </product>
that's great, but want add above xml existing document, not create new document. according nokogiri documentation, can done using builder's with
method, so:
builder = nokogiri::xml::builder.with(document.at('products')) |xml| xml.product { xml.test "hi" } end puts builder
when this, however, xml gets put single line no indentation. looks this:
<products><product><test>hi</test></product></products>
am missing format correctly?
found answer in nokogiri mailing list:
in xml, whitespace can considered meaningful. if parse document contains whitespace nodes, libxml2 assume whitespace nodes meaningful , not insert them you.
you can tell libxml2 whitespace not meaningful passing "noblanks" flag parser. demonstrate, here example reproduces error, want:
require 'nokogiri' def build_from node builder = nokogiri::xml::builder.with(node) do|xml| xml.hello xml.world end end end xml = data.read doc = nokogiri::xml(xml) puts build_from(doc.at('bar')).to_xml doc = nokogiri::xml(xml) { |x| x.noblanks } puts build_from(doc.at('bar')).to_xml
output:
<root> <foo> <bar> <baz /> </bar> </foo> </root>
Comments
Post a Comment