Reputation: 1267
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
Upvotes: 0
Views: 1590
Reputation: 3706
Nokogiri::XML::Builder
is 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:
doc = Nokogiri::XML(IO.read("test.xml"))
name_node = Nokogiri::XML::Node.new("name",doc)
name_node.content = "Name"
data_node = Nokogiri::XML::Node.new("data",doc)
data_node.add_child(name_node)
doc.root.add_child(data_node)
file = File.open("test.xml",'w')
file.puts doc.to_xml
file.close
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::Builder
to create everything downside from and including data, this would be an example for this combined approach:
builder = Nokogiri::XML::Builder.new do
data do
name "Name"
end
end
doc = Nokogiri::XML(IO.read("test.xml"))
doc.root.add_child builder.doc.root
file = File.open("test.xml",'w')
file.puts doc.to_xml
file.close
Upvotes: 5