Ram Laxman Yadav bio photo

Ram Laxman Yadav

Ruby on Rails Developer

Email Twitter LinkedIn Github Stackoverflow

I am using gem nokogiri for Nokogiri::XML::Node manipulations.here are the some examples of performing the basics operations on the Nokogiri::XML::Node.you can perform these operations with Nokogiri::XML::Node.

Say for the example you have the Nokogiri::XML::Node named node,now here are some basic operation with this node.

####1. Get parent:

node.parent #=> will return of the xpath of the node in document.

####2. Get xpath:

node.path #=>will return of the xpath of the node in document

####3. Get node at some path in document:

_node = doc.xpath('some_path')
 #=>where doc is a nokogiri document.it will return a nodeset if you want to get the exact node then do this.
 _node = doc.xpath('some_path')[0] or _node = doc.xpath('some_path').first

####4. Get children:

node.children
 #=>will return the ```nodeset``` of childs of node your can select them according to your need.

####5. Add children:

node.add_child('child_html')
 #=> add child in as the last child.

####6. Add siblings:

node.add_next_sibling('some_html') #=>  add a sibling node after the node in parent.
node.add_previous_sibling('some_html') #=>  add a sibling node before the node in parent node.

####7. Replace a node:

node.replace("replace_node's_html") #=> replace a node by given html.

####8. Styling a node:

node['class'] = 'some_css_class' #=>  add a css class to node.
css_class = node['class']  #=>  get the css_class of the node.

####9. Show html:

node.to_html  #=>  will return html of the node.

Thanks for reading this.

Enjoy!!!