Donato
Donato

Reputation: 2777

append xml node to the document with nokogiri

I want to append a node to the document, but as a child of the body node. When I use << or push, it simply adds the node after the body node, not as a child of it:

xml = zip.read("word/document.xml")
doc = Nokogiri::XML(xml) {|x| x.noent}
body = doc.xpath("//w:body")
node = Nokogiri::XML::Node.new("<w:p w14:paraId=\"322D15A5\" w14:textId=\"3D86357C\" w:rsidR=\"00E1538A\" w:rsidRDefault=\"002D3A2C\">Hello World\n</w:p>",doc)
body << node

How can I add the node as a child of body rather than a sibling?

Upvotes: 2

Views: 859

Answers (1)

Donato
Donato

Reputation: 2777

I figured it out. body is the Nokogiri::XML::NodeSet container. It is intuitive to think you would append it to that, but that didn't work. When you reached one level deeper, you get the body element itself:

> body.first.class
=> Nokogiri::XML::Element 

And for better or wose, by appending to the new node to that body node:

body.first << node

You get the desired nested result.

Upvotes: 2

Related Questions