加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 03:38:08 所属栏目:百科 来源:网络整理
导读:我正在使用 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/
我正在使用 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读