如何使用Nokogiri和Ruby替换现有xml中的值?

时间:2014-04-25 14:59:02

标签: ruby xml xpath nokogiri

我正在使用Ruby 1.9.3和最新的Nokogiri宝石。我已经研究了如何使用xpath从xml中提取值并指定元素的路径(?)。这是我的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<File xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Houses>
        <Ranch>
            <Roof>Black</Roof>
            <Street>Markham</Street>
            <Number>34</Number>
        </Ranch>
    </Houses>
</File>

我使用此代码打印一个值:

doc = Nokogiri::XML(File.open ("C:\\myfile.xml"))  
puts doc.xpath("//Ranch//Street")

哪个输出:

<Street>Markham</Street>

这一切都运行正常但我需要的是写/替换值。我想使用相同类型的路径样式查找来传递值来替换那里的值。所以我想将街道名称传递给此路径并覆盖那里的街道名称。我一直在互联网上,但只能找到创建新XML或在文件中插入一个全新节点的方法。有没有办法像这样按行替换值?感谢。

1 个答案:

答案 0 :(得分:8)

你想要content= method

  

将Node的内容设置为包含string的Text节点。字符串获取XML转义,而不是解释为标记。

请注意xpath返回NodeSet而不是单个Node,因此您需要使用at_xpath或以其他方式获取单个节点:

doc = Nokogiri::XML(File.open ("C:\\myfile.xml"))  
node = doc.xpath("//Ranch//Street")[0] # use [0] to select the first result
node.content = "New value for this node"

puts doc # produces XML document with new value for the node
相关问题