ruby - How I can add an element? -


i'm doing this:

targets = @xml.xpath("./target") if targets.empty?   targets << nokogiri::xml::node.new('target', @xml) end 

however @xml still without target. can in order update original @xml?

it's lot easier that:

require 'nokogiri'  doc = nokogiri::xml(<<eot) <root>   <node>   </node> </root> eot  doc.at('node').children = '<child>foo</child>' doc.to_xml # => "<?xml version=\"1.0\"?>\n<root>\n  <node><child>foo</child></node>\n</root>\n" 

children= smart enough see you're passing in , dirty work you. use string define new node(s) , tell nokogiri insert it.


doc.at('node').class   # => nokogiri::xml::element doc.at('//node').class # => nokogiri::xml::element  doc.search('node').first   # => #<nokogiri::xml::element:0x3fd1a88c5c08 name="node" children=[#<nokogiri::xml::text:0x3fd1a88eda3c "\n  ">]> doc.search('//node').first # => #<nokogiri::xml::element:0x3fd1a88c5c08 name="node" children=[#<nokogiri::xml::text:0x3fd1a88eda3c "\n  ">]> 

search generic "find node" method take either css or xpath selectors. at equivalent search('some selector').first. at_css , at_xpath specific equivalents of at, css , xpath search. use specific versions if want, in general use generic versions.


you can't use:

targets = @xml.xpath("./target") if targets.empty?   targets << nokogiri::xml::node.new('target', @xml) end 

targets [] (actually empty nodeset) if ./target doesn't exist in dom. can't append node [], because nodeset doesn't have idea of you're talking about, resulting in undefined method 'children=' nil:nilclass (nomethoderror) exception.

instead must find specific location want insert node. at since finds first location. of course, if want multiple places modify use search iterate on returned nodeset , modify based on individual nodes returned.


Comments

Popular posts from this blog

powershell Start-Process exit code -1073741502 when used with Credential from a windows service environment -

twig - Using Twigbridge in a Laravel 5.1 Package -

c# - LINQ join Entities from HashSet's, Join vs Dictionary vs HashSet performance -