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

我正在使用 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或在文件中插入一个全新节点的方法.有没有办法像这样按行替换值?谢谢.

解决方法

你想要 content= method

Set the Node’s content to a Text node containing string. The string gets XML escaped,not interpreted as markup.

请注意,xpath返回NodeSet而不是单个节点,因此您需要使用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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...