[英]open xml file with nokogiri update node and save
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文件,按id搜索,替换节点中的值,然后重新保存文档。
my xml 我的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"
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
. node_update.inner_html = "true"
在inner_html
上返回方法错误。 then after that saving the updated file. 然后保存更新的文件。
First of all, your node_update
is actually a NodeSet
, not the Node
that you probably think it is. 首先,您的node_update
实际上是一个NodeSet
,而不是您可能认为的Node
。 You need a Node
if you want to call inner_html=
on it: 如果要在其上调用inner_html=
,则需要一个Node
:
node_update[0].inner_html = 'true'
Then writing out the updated XML is just a bit of standard file manipulating combined with a to_xml
call: 然后写出更新的XML只是一些标准文件操作和to_xml
调用的结合:
File.open('whatever.xml', 'w') { |f| f.print(doc.to_xml) }
As an aside, your input isn't valid XML. 顺便说一句,您的输入不是有效的XML。 You have a </details>
but no <details>
. 您有</details>
但没有<details>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.