Working with Nokogiri::XML::Node in Rails

Posted by : on

Category : Rails

I am using gem nokogiri for Nokogiri::XML::Node are the some examples of performing the basics operations on the 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 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:

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

5. Add children:

 #=> 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.


About Ram Laxman Yadav
Ram Laxman Yadav

Senior Software Engineering Professional | Tech Enthusiast | Mentor | Payments | Hospitality | E-Commerce, based in NCR, India

Email :

Website :