Is it possible to use Nokogiri to create XML or HTML files from scratch?

Yes, Nokogiri is not just for parsing XML or HTML; it can also be used to create XML or HTML files from scratch. Nokogiri is a Ruby gem that provides an easy-to-use interface for parsing, querying, and modifying XML and HTML documents.

Here's how you can create an XML file from scratch using Nokogiri in Ruby:

require 'nokogiri'

# Create a new XML document
builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.products {
      xml.widget {
        xml.id_ "10"
        xml.name "Awesome Widget"
      }
    }
  }
end

# Write to a file
File.open("output.xml", "w") do |file|
  file.write(builder.to_xml)
end

The above code will create an XML file with the following structure:

<?xml version="1.0"?>
<root>
  <products>
    <widget>
      <id>10</id>
      <name>Awesome Widget</name>
    </widget>
  </products>
</root>

Similarly, you can create an HTML file from scratch. Here's an example:

require 'nokogiri'

# Create a new HTML document
builder = Nokogiri::HTML::Builder.new do |html|
  html.html {
    html.head {
      html.title "My Test Page"
    }
    html.body {
      html.h1 "This is a heading"
      html.p "This is a paragraph with some text."
    }
  }
end

# Write to a file
File.open("output.html", "w") do |file|
  file.write(builder.to_html)
end

This will produce an HTML file with the following contents:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>My Test Page</title>
  </head>
  <body>
    <h1>This is a heading</h1>
    <p>This is a paragraph with some text.</p>
  </body>
</html>

When using Nokogiri to create XML or HTML files, you have the ability to structure the document as you see fit, add attributes, nest elements, and include text content. The Nokogiri::XML::Builder and Nokogiri::HTML::Builder classes provide a DSL (domain-specific language) for building XML and HTML documents, respectively.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon