2

I'm trying to add a few elements to an already existing XML document. The following code is successful at adding the desired nodes and content, however it doesn't format the inserted elements. All the added elements end up on one line instead of with line breaks and indentations after each element.

Any suggestions about how I could add this formatting?

The code is:

doc.xpath("//tei:div[@xml:id='versionlog']", {"tei" => "http://www.tei-c.org/ns/1.0"}).each do |node|
  new_entry = Nokogiri::XML::Node.new "div", doc
  new_entry["xml:id"] = "v_#{ed_no}"
  head = Nokogiri::XML::Node.new "head", doc
  head.content = "Description of changes for #{ed_no}"
  new_entry.add_child(head)
  para = Nokogiri::XML::Node.new "p", doc
  para.content = "#{version_description}"
  new_entry.add_child(para)
  node.add_child(new_entry)
end
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Jeff
  • 3,943
  • 8
  • 45
  • 68

1 Answers1

1

Why is it important that the XML not be on one line? It's purely cosmetic having "pretty-printed" XML, and not required by the XML spec or the parser when the XML is reloaded. Personally, I'd recommend having no formatting for your transfer speed and reduced disk size, but YMMV.

You can either run the XML through an XML beautifier, or play a game with Nokogiri along the lines of:

new_entry.add_child(para.to_xml + "\n")

The line break will be added as a text node between the tags, but it's benign and not significant to XML's ability to deliver its payload.

If you insist, "How do I pretty-print HTML with Nokogiri?" describes how to get there.

Community
  • 1
  • 1
the Tin Man
  • 158,662
  • 42
  • 215
  • 303