open xml file with nokogiri update node and save

让人想犯罪 __ 提交于 2019-12-01 11:12:02

问题


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.

my 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.


回答1:


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'

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) }

As an aside, your input isn't valid XML. You have a </details> but no <details>.



来源:https://stackoverflow.com/questions/16909290/open-xml-file-with-nokogiri-update-node-and-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!