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

use*_*786 5 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>
Run Code Online (Sandbox Code Playgroud)

我用这段代码打印一个值:

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

哪个输出:

<Street>Markham</Street>
Run Code Online (Sandbox Code Playgroud)

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

mat*_*att 8

你想要的content=方法:

将Node的内容设置为包含的Text节点string.该字符串获取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
Run Code Online (Sandbox Code Playgroud)