本文介绍了如何向 XML 添加新节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 XML 文件,items.xml:

I have a simple XML file, items.xml:

 <?xml version="1.0" encoding="UTF-8" ?>

<items>
  <item>
    <name>mouse</name>
    <manufacturer>Logicteh</manufacturer>
  </item>
  <item>
    <name>keyboard</name>
    <manufacturer>Logitech - Inc.</manufacturer>
  </item>
  <item>
    <name>webcam</name>
    <manufacturer>Logistech</manufacturer>
  </item>
</items>

我正在尝试使用以下代码插入一个新节点:

I am trying to insert a new node with the following code:

require 'rubygems'
require 'nokogiri'

f = File.open('items.xml')
@items = Nokogiri::XML(f)
f.close

price = Nokogiri::XML::Node.new "price", @items
price.content = "10"

@items.xpath('//items/item/manufacturer').each do |node|
  node.add_next_sibling(price)
end

file = File.open("items_fixed.xml",'w')
file.puts @items.to_xml
file.close

但是这段代码只在最后一个节点之后添加了一个新节点,items_fixed.xml:

However this code adds a new node only after the last <manufacturer> node, items_fixed.xml:

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <item>
    <name>mouse</name>
    <manufacturer>Logitech</manufacturer>
  </item>
  <item>
    <name>keyboard</name>
    <manufacturer>Logitech</manufacturer>
  </item>
  <item>
    <name>webcam</name>
    <manufacturer>Logitech</manufacturer><price>10</price>
  </item>
</items>

为什么?

推荐答案

区分 Node(位于树中特定位置的特定结构化 XML 数据)、以及作为数据结构的节点模板".

It would be helpful to distinguish between a Node (a particular piece of structured XML data at a particular place in a tree), and a "node template" which is the structure of the data.

Nokogiri(和大多数其他 XML 库)只允许您指定 Node,而不是节点模板.因此,当您创建 price = Nokogiri::XML::Node.new "price", @items 时,您拥有属于特定地点的特定数据,但尚未定义该地点

Nokogiri (and most other XML libraries) only allow you to specify Nodes, not node templates. So when you created price = Nokogiri::XML::Node.new "price", @items, you had a particular piece of data that belongs in a particular place, but hadn't defined the place yet.

当您将它添加到第一个 时,您就定义了它的位置.当您将它添加到第二个 时,您将它从原来的位置连根拔起,并将其放在一个新位置.那时这个 Node 只出现在第二个 中.当您向每个项目添加相同的 Node 时,这种情况会继续下去,直到到达最后一个 ,这是节点所在的位置.

When you added it to the first <item>, you defined its place. When you added it to the second <item>, you uprooted it from its place and put it in a new place. At that point this Node appeared only in the second <item>. This continues when you add the same Node to each item, until you reach the last <item>, which is where the node stays.

Nokogiri 无法指定节点模板.您需要做的是:

Nokogiri doesn't have any way to specify a node template. What you need to do is:

@items.xpath('//items/item/manufacturer').each do |node|
  price = Nokogiri::XML::Node.new "price", @items
  price.content = "10"
  node.add_next_sibling(price)
end

这篇关于如何向 XML 添加新节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 20:21