Skip to content

Instantly share code, notes, and snippets.

@tkuchiki
Created November 7, 2013 02:05
Show Gist options
  • Save tkuchiki/7347736 to your computer and use it in GitHub Desktop.
Save tkuchiki/7347736 to your computer and use it in GitHub Desktop.
nokogiri add_chlid and remove child to xml
#!/usr/bin/ruby
require 'nokogiri'
@file = File.open("/path/to/test.xml")
@xml = Nokogiri::XML(@file)
@file.close
@xml.at("hoge").children.remove
puts "# remove hoge children"
puts @xml
@fuga = Nokogiri::XML::Node.new "fuga", @xml
@fuga.content = "new content"
@xml.at("hoge").add_child(@fuga)
puts "# add_child at hoge"
puts @xml
# remove hoge children
<?xml version="1.0"?>
<root>
<hoge/>
<foo>
<piyo>1</piyo>
</foo>
</root>
# add_child at hoge
<?xml version="1.0"?>
<root>
<hoge><fuga>new content</fuga></hoge>
<foo>
<piyo>1</piyo>
</foo>
</root>
<root>
<hoge>
<fuga>1</fuga>
<fuga>2</fuga>
<fuga>3</fuga>
</hoge>
<foo>
<piyo>1</piyo>
</foo>
</root>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment