使用 nokogiri 更新节点打开 xml 文件并保存 [英] open xml file with nokogiri update node and save
问题描述
我正在尝试弄清楚如何打开一个 xml 文件,通过一个 id 搜索,替换节点中的一个值,然后重新保存文档.
I'm trying to figure out how to open an xml file, search by an id, replace a value in the node and then resave the document.
我的 xml
<?xml version="1.0"?>
<data>
<user id="1370018670618">
<email>1@1.com</email>
<sent>false</sent>
</user>
<user id="1370018701357">
<email>2@2.com</email>
<sent>false</sent>
</user>
<user id="1370018769724">
<email>3@3.com</email>
<sent>false</sent>
</user>
<user id="1370028546850">
<email>4@4.com</email>
<sent>false</sent>
</user>
<user id="1370028588345">
<email>5@5.com</email>
<sent>false</sent>
</user>
</data>
我打开和查找节点的代码
My code to open and find a node
xml_content = File.read("/home/mike/app/users.xml")
doc = Nokogiri::XML(xml_content)
node_update = doc.search("//user[@id='1370028588345'] //sent")
node_update.inner_html ##returns value of "sent"
我陷入困境的部分实际上是更新节点.node_update.inner_html = "true"
在 inner_html
上返回一个方法错误.然后保存更新的文件.
the part in this where I'm stuck is actually updating the node. node_update.inner_html = "true"
returns a method error on inner_html
. then after that saving the updated file.
推荐答案
首先,你的 node_update
实际上是一个 NodeSet
,而不是 Node
你可能认为它是.如果您想在其上调用 inner_html=
,您需要一个 Node
:
First of all, your node_update
is actually a NodeSet
, not the Node
that you probably think it is. You need a Node
if you want to call inner_html=
on it:
node_update[0].inner_html = 'true'
然后写出更新的 XML 只是一些标准文件操作结合 to_xml
调用:
Then writing out the updated XML is just a bit of standard file manipulating combined with a to_xml
call:
File.open('whatever.xml', 'w') { |f| f.print(doc.to_xml) }
<小时>
顺便说一句,您的输入不是有效的 XML.您有 但没有
.
这篇关于使用 nokogiri 更新节点打开 xml 文件并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!