Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 在Nokogiri中合并两个XML文件_Ruby_Xml_Nokogiri - Fatal编程技术网

Ruby 在Nokogiri中合并两个XML文件

Ruby 在Nokogiri中合并两个XML文件,ruby,xml,nokogiri,Ruby,Xml,Nokogiri,有一些帖子是关于这个话题的,但我没能想出如何解决我的问题 我有两个XML文件: <Products> <Product> <some> <value></value> </some> </Product> <Product> <more> <data></data> </more>

有一些帖子是关于这个话题的,但我没能想出如何解决我的问题

我有两个XML文件:

<Products>
  <Product>
    <some>
      <value></value>
    </some>
  </Product>
  <Product>
    <more>
      <data></data>
    </more>
  </Product>
</Products>

以及:


我想生成一个如下所示的XML文档:

<Products>
  <Product>
    <some>
      <value></value>
    </some>
  </Product>
  <Product>
    <more>
      <data></data>
    </more>
  </Product>
  <Product>
    <some_other>
      <value></value>
    </some_other>
  </Product>
</Products>

每个节点
都应该合并到

我尝试使用以下方法创建新文档:

doc = Nokogiri::XML("<Products></Products>")
nodes = files.map { |xml| Nokogiri::XML(xml).xpath("//Product") }
set = Nokogiri::XML::NodeSet.new(doc, nodes)
doc=Nokogiri::XML(“”)
nodes=files.map{| xml | Nokogiri::xml(xml).xpath(“//Product”)}
set=Nokogiri::XML::NodeSet.new(文档,节点)
但这会引发一个错误:
ArgumentError:node必须是Nokogiri::XML::node或Nokogiri::XML::Namespace


我想我不理解
NodeSet
,但我不知道如何合并这两个XML文件。

您的示例代码不会生成您想要的内容,因为在执行以下操作时,您会丢弃一些
和更多
节点:

doc = Nokogiri::XML("<Products></Products>")
将它们作为
产品的子项添加到原始文档中

doc.at('Products').add_child(new_products)
这导致
doc
中的DOM看起来像:

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>
将文档放入xml
# >> 
# >> 
# >>   
# >>     
# >>       
# >>     
# >>   
# >>   
# >>     
# >>       
# >>     
# >>   
# >> 
# >>     
# >>       
# >>     
# >>   

好吧,我并不反对让您做大量工作来解决问题,因为这是我必须做的,但在这里查看了几个相关问题后,我发现没有一个问题是您想要做的,所以我想我最好帮助记录这一过程。:-)不过我很高兴这有帮助。XML/HTML操作可能会让人困惑,但一旦您了解了这些技巧以及Nokogiri如何提供帮助,就很容易了。
new_products = Nokogiri::XML(xml2).search('Product')
doc.at('Products').add_child(new_products)
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>