From a String
- From a File
- From the Internet
- Parse Options
- Encoding
Original: Parsing an html/xml Document
Parsing a html/xml document reading from a string
We ' ve tried to make this easy on. really! We ' re here for make your life easier.
1 html_doc = nokogiri::html ("")2 xml_doc = Nokogiri::xml ("< Root><aliens><alien><name>alf</name></alien></aliens></root> ")
Variables html_doc
and xml_doc
is Nokogiri object 1, with a variety of properties and methods, see this. These details are described in other chapters.
* * Original documents, translated as "objects"
read from File
No need to read files to strings. The Nokogiri will do the work.
1 doc = File.Open ("blossom.xml") {|f| Nokogiri::xml (f)}
read from Network
1 ' Open-uri ' 2 doc = nokogiri::html (open ("http://www.threescompany.com/"))
parse option (Parse options)
Nokogiri provides some options that affect how you parse it. See: Read about them here, the following are the most commonly used options:
NOBLANKS
-Remove Blank Nodes
NOENT
-Substitute Entities
NOERROR
-Suppress error reports
STRICT
-Strict parsing; Raise an error when parsing malformed documents
NONET
-Prevent any network connections during parsing. Recommended for parsing untrusted documents.
Usage:
1 doc = Nokogiri::xml (File.Open ("blossom.xml")) do |config| 2 config.strict.nonet3 End
Or
1 doc = Nokogiri::xml (File.Open ("blossom.xml")) do |config| 2 Config.options = nokogiri::xml::P arseoptions::strict | nokogiri::xml::P arseoptions::nonet 3 End
Coding
Inside the program, strings are stored normally in UTF-8 encoding. A method that returns a text value returns a UTF-8 string. Methods that return XML (for example, To_xml, to_html, inner_html) return a string that is encoded the same way as the source file.
Note/WARNING
Some documents declare specific encodings, but they are actually used in a different way. Which encoding does the parser use in this case?
The so-called data is simply a long string consisting of one byte. We have added meaning to it artificially. The same set of bytes represents a number of distinct characters under different encodings, so it is not possible to infer the encoding 100% accurately. Even a fairly good LIBXML2 library cannot always successfully infer the encoding.
The best way for Nokogiri to use the correct encoding to process the document is to display the set code. Here's an example:
1 doc = nokogiri.xml ('<foo><bar/><foo>'euc-jp ')
Due to the limited level of translators, there may be omissions and irregularities in the translation, and it is welcome to correct them in the comments section.
Translation [Ruby Tutorial] Nokogiri-Parsing Html/xml Documents/parsing an html/xml document