Combine two XML files in Nokigiri
There are several posts on this topic, but I couldn't figure out how to solve my problem.
I have two XML files:
<Products>
<Product>
<some>
<value></value>
</some>
</Product>
<Product>
<more>
<data></data>
</more>
</Product>
</Products>
and
<Products>
<Product>
<some_other>
<value></value>
</some_other>
</Product>
</Products>
I want to create an XML document that looks like this:
<Products>
<Product>
<some>
<value></value>
</some>
</Product>
<Product>
<more>
<data></data>
</more>
</Product>
<Product>
<some_other>
<value></value>
</some_other>
</Product>
</Products>
Each node <Product>
must be concatenated with <Products>
.
I tried to create a new document using:
doc = Nokogiri::XML("<Products></Products>")
nodes = files.map { |xml| Nokogiri::XML(xml).xpath("//Product") }
set = Nokogiri::XML::NodeSet.new(doc, nodes)
but it causes an error: ArgumentError: node must be a Nokogiri::XML::Node or Nokogiri::XML::Namespace
.
I think I don't understand NodeSet
, but I cannot figure out how to combine these two XML files.
source to share
Your example code will not generate what you want because you are dropping your nodes some
and more
when you do:
doc = Nokogiri::XML("<Products></Products>")
Instead of creating an empty DOM, you need to copy the original and just add new nodes to it:
require 'nokogiri'
xml1 = '<Products>
<Product>
<some>
<value></value>
</some>
</Product>
<Product>
<more>
<data></data>
</more>
</Product>
</Products>
'
xml2 = '<Products>
<Product>
<some_other>
<value></value>
</some_other>
</Product>
</Products>
'
doc = Nokogiri::XML(xml1)
Find the new nodes to add Product
:
new_products = Nokogiri::XML(xml2).search('Product')
Add them to the original document as added children Products
:
doc.at('Products').add_child(new_products)
The resulting DOM doc
looks like this:
puts doc.to_xml
# >> <?xml version="1.0"?>
# >> <Products>
# >> <Product>
# >> <some>
# >> <value/>
# >> </some>
# >> </Product>
# >> <Product>
# >> <more>
# >> <data/>
# >> </more>
# >> </Product>
# >> <Product>
# >> <some_other>
# >> <value/>
# >> </some_other>
# >> </Product></Products>
source to share