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
. then after that saving the updated file.
我被困在这里的部分实际上是更新节点。node_update。inner_html = "true"返回inner_html上的方法错误。然后保存更新后的文件。
1 个解决方案
#1
8
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实际上是一个节点集,而不是您可能认为的节点。如果要在节点上调用inner_html=,需要一个节点:
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. You have a </details>
but no <details>
.
顺便说一句,您的输入不是有效的XML。您有一个,但是没有
#1
8
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实际上是一个节点集,而不是您可能认为的节点。如果要在节点上调用inner_html=,需要一个节点:
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. You have a </details>
but no <details>
.
顺便说一句,您的输入不是有效的XML。您有一个,但是没有