I’m trying to extend an existing XML file and add a new node. I’m loading the XML containing a lot of products, add a new one and save it.
I’m using Nokogiri and Ruby 1.9.3.
This is the best that I created:
builder = Nokogiri::XML::Builder.new do
root do
load_xml = Nokogiri::XML(IO.read("test.xml"))
parent.add_child(load_xml.root)
data do
name "Name"
end
end
end
file = File.open("test.xml",'w')
file.puts builder.to_xml
file.close
Nokogiri::XML::Builderis actually only used when creating new XML-Files, not when editing them.Also your code loads the XML and puts it into a new root-Node (root) while it appends a new child (the data-node) to it. Is this really the desired behaviour?
Normally you would do adding a node like this:
This is without creating a new root node, because this seems a little bit
peculiar to me…
Also you might want to try the Nokogiri-Documentation, it is fairly extensive.
There are other ways, which would use
Nokogiri::XML::Builderto create everything downside from and including data, this would be an example for this combined approach: