Domanda

I have the next tags

    <svg><text id="text1" color="red">Hello!</text>
         <text id="text2" color="red">Another text </text></svg>

How can i do with Nokogiri to change the content between the tags, so i get

 <svg>   <text id="text1" color="red">Goodbye</text>
        <text id="text2" color="red">Another text </text></svg>

Is there a method like this??

document.at_xpath('//svg/text[@id="text1"]').text="Goodbye"
È stato utile?

Soluzione

Do as below using Nokogiri::XML::Node#content=:

Set the Node’s content to a Text node containing string. The string gets XML escaped, not interpreted as markup.

document.at_xpath('//svg/text[@id="text1"]').content = "Goodbye"

Altri suggerimenti

Selecting by id would be another solution, possibly more elegant for HTML:

require 'nokogiri'

html = %q{ 
  <html>
   <body>
    <svg><text id="text1" color="red">Hello!</text>
     <text id="text2" color="red">Another text </text></svg>   </body>
 </html>
}

doc = Nokogiri::XML(html)
hello = doc.at_css('#text1')
hello.content = "Goodbye"

puts doc
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top