How can I use Nokogiri with Ruby to replace values ​​in existing xml?

I am using Ruby 1.9.3 with the latest Nokogiri gem. I developed how to extract values ​​from xml using xpath and specify the path (?) To the element. Here is the XML file that I have:

<?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>

I use this code to print the values:

doc = Nokogiri::XML(File.open ("C:\\myfile.xml"))  
puts doc.xpath("//Ranch//Street")

What outputs:

<Street>Markham</Street>

This all works fine, but I need to write / replace the value. I want to use the same type of path-style search to pass in the value that needs to be replaced. Therefore, I want to transfer the name of the street to this path and rewrite the name of the street that is. I have been everywhere on the Internet, but can find ways to create new XML or insert a completely new node into the file. Is there a way to replace values ​​on a row like this? Thank.

+4
1

content=:

Node node. XML-, .

, xpath NodeSet Node, at_xpath node - :

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
+6

Source: https://habr.com/ru/post/1538086/


All Articles