# Nokogiri usage

**URL:** <https://rubytalk.org/t/nokogiri-usage/55929>\
**Category:** ruby-talk\
**Created:** [25 October 2009 09:31 UTC](https://rubytalk.org/t/nokogiri-usage/55929 "2009-10-25T09:31:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Fernando\_Perez](https://avatars.discourse-cdn.com/v4/letter/f/8797f3/32.png) [@Fernando\_Perez](https://rubytalk.org/u/Fernando_Perez)\
**Post date:** [25 October 2009 09:31 UTC](https://rubytalk.org/t/nokogiri-usage/55929/1 "2009-10-25T09:31:55Z")

</div>

Hi,

In one of my Rails app, I have a content attribute that hosts some html  
code. I want to parse this content and replace \<img\> tags by something  
else. I used to do Nokogiri::HTML(content), and then do my parsing, then  
return the content.

The problem is that nokogiri injects the doctype and \<html\>\<body\> tags  
which obviously messes up my final html page because of these duplicate  
tags.

So how to perform the parsing without having to first initialize the  
content with Nokogiri::HTML, or how to not initialize a full html page

Cheers,

> **···**
>
> from my content?  
> --  
> Posted via [http://www.ruby-forum.com/](http://www.ruby-forum.com/).

---

<div class="post-metadata">

**Author:** ![Mike\_Dalessio1](https://yyz1.discourse-cdn.com/flex029/user_avatar/rubytalk.org/mike_dalessio1/32/1903_2.png) [@Mike\_Dalessio1](https://rubytalk.org/u/Mike_Dalessio1)\
**Post date:** [25 October 2009 17:32 UTC](https://rubytalk.org/t/nokogiri-usage/55929/2 "2009-10-25T17:32:07Z")

</div>

> Hi,
> 
> In one of my Rails app, I have a content attribute that hosts some html  
> code. I want to parse this content and replace \<img\> tags by something  
> else. I used to do Nokogiri::HTML(content), and then do my parsing, then  
> return the content.
> 
> The problem is that nokogiri injects the doctype and \<html\>\<body\> tags  
> which obviously messes up my final html page because of these duplicate  
> tags.
> 
> So how to perform the parsing without having to first initialize the  
> content with Nokogiri::HTML, or how to not initialize a full html page  
> from my content?

Try Nokogiri::HTML::DocumentFragment.parse(content).

> **···**
>
> On Sun, Oct 25, 2009 at 5:31 AM, Fernando Perez \<pedrolito@lavache.com\>wrote:
> 
> > Cheers,  
> > --  
> > Posted via [http://www.ruby-forum.com/\](http://www.ruby-forum.com/%5C).
> 
> --  
> mike dalessio  
> mike@csa.net
