

Nokogiri
========

 * [README](https://nokogiri.org/rdoc/README_md.html)

 * [Nokogiri](nokogiri)
* [Nokogiri::CSS](nokogiri/css)
* [Nokogiri::CSS::SyntaxError](nokogiri/css/syntaxerror)
* [Nokogiri::CSS::XPathVisitor](nokogiri/css/xpathvisitor)
* [Nokogiri::CSS::XPathVisitor::BuiltinsConfig](nokogiri/css/xpathvisitor/builtinsconfig)
* [Nokogiri::CSS::XPathVisitor::DoctypeConfig](nokogiri/css/xpathvisitor/doctypeconfig)
* [Nokogiri::ClassResolver](nokogiri/classresolver)
* [Nokogiri::Decorators](nokogiri/decorators)
* [Nokogiri::Decorators::Slop](nokogiri/decorators/slop)
* [Nokogiri::EncodingHandler](nokogiri/encodinghandler)
* [Nokogiri::Gumbo](nokogiri/gumbo)
* [Nokogiri::HTML](nokogiri/html4)
* [Nokogiri::HTML4](nokogiri/html4)
* [Nokogiri::HTML4::Builder](nokogiri/html4/builder)
* [Nokogiri::HTML4::Document](nokogiri/html4/document)
* [Nokogiri::HTML4::DocumentFragment](nokogiri/html4/documentfragment)
* [Nokogiri::HTML4::ElementDescription](nokogiri/html4/elementdescription)
* [Nokogiri::HTML4::EntityDescription](nokogiri/html4/entitydescription)
* [Nokogiri::HTML4::EntityLookup](nokogiri/html4/entitylookup)
* [Nokogiri::HTML4::SAX](nokogiri/html4/sax)
* [Nokogiri::HTML4::SAX::Parser](nokogiri/html4/sax/parser)
* [Nokogiri::HTML4::SAX::ParserContext](nokogiri/html4/sax/parsercontext)
* [Nokogiri::HTML4::SAX::PushParser](nokogiri/html4/sax/pushparser)
* [Nokogiri::HTML5](nokogiri/html5)
* [Nokogiri::HTML5::Document](nokogiri/html5/document)
* [Nokogiri::HTML5::DocumentFragment](nokogiri/html5/documentfragment)
* [Nokogiri::HTML5::Node](nokogiri/html5/node)
* [Nokogiri::HTML5::QuirksMode](nokogiri/html5/quirksmode)
* [Nokogiri::HTML::Builder](nokogiri/html/builder)
* [Nokogiri::HTML::Document](nokogiri/html/document)
* [Nokogiri::HTML::DocumentFragment](nokogiri/html/documentfragment)
* [Nokogiri::SyntaxError](nokogiri/syntaxerror)
* [Nokogiri::XML](nokogiri/xml)
* [Nokogiri::XML::Attr](nokogiri/xml/attr)
* [Nokogiri::XML::AttributeDecl](nokogiri/xml/attributedecl)
* [Nokogiri::XML::Builder](nokogiri/xml/builder)
* [Nokogiri::XML::CDATA](nokogiri/xml/cdata)
* [Nokogiri::XML::CharacterData](nokogiri/xml/characterdata)
* [Nokogiri::XML::Comment](nokogiri/xml/comment)
* [Nokogiri::XML::DTD](nokogiri/xml/dtd)
* [Nokogiri::XML::Document](nokogiri/xml/document)
* [Nokogiri::XML::DocumentFragment](nokogiri/xml/documentfragment)
* [Nokogiri::XML::Element](nokogiri/xml/element)
* [Nokogiri::XML::ElementContent](nokogiri/xml/elementcontent)
* [Nokogiri::XML::ElementDecl](nokogiri/xml/elementdecl)
* [Nokogiri::XML::EntityDecl](nokogiri/xml/entitydecl)
* [Nokogiri::XML::EntityReference](nokogiri/xml/entityreference)
* [Nokogiri::XML::Namespace](nokogiri/xml/namespace)
* [Nokogiri::XML::Node](nokogiri/xml/node)
* [Nokogiri::XML::Node::SaveOptions](nokogiri/xml/node/saveoptions)
* [Nokogiri::XML::NodeSet](nokogiri/xml/nodeset)
* [Nokogiri::XML::Notation](nokogiri/xml/notation)
* [Nokogiri::XML::ParseOptions](nokogiri/xml/parseoptions)
* [Nokogiri::XML::ProcessingInstruction](nokogiri/xml/processinginstruction)
* [Nokogiri::XML::Reader](nokogiri/xml/reader)
* [Nokogiri::XML::RelaxNG](nokogiri/xml/relaxng)
* [Nokogiri::XML::SAX](nokogiri/xml/sax)
* [Nokogiri::XML::SAX::Document](nokogiri/xml/sax/document)
* [Nokogiri::XML::SAX::Parser](nokogiri/xml/sax/parser)
* [Nokogiri::XML::SAX::Parser::Attribute](nokogiri/xml/sax/parser/attribute)
* [Nokogiri::XML::SAX::ParserContext](nokogiri/xml/sax/parsercontext)
* [Nokogiri::XML::SAX::PushParser](nokogiri/xml/sax/pushparser)
* [Nokogiri::XML::Schema](nokogiri/xml/schema)
* [Nokogiri::XML::Searchable](nokogiri/xml/searchable)
* [Nokogiri::XML::SyntaxError](nokogiri/xml/syntaxerror)
* [Nokogiri::XML::Text](nokogiri/xml/text)
* [Nokogiri::XML::XPath](nokogiri/xml/xpath)
* [Nokogiri::XML::XPath::SyntaxError](nokogiri/xml/xpath/syntaxerror)
* [Nokogiri::XML::XPathContext](nokogiri/xml/xpathcontext)
* [Nokogiri::XSLT](nokogiri/xslt)
* [Nokogiri::XSLT::Stylesheet](nokogiri/xslt/stylesheet)
* [Object](https://nokogiri.org/rdoc/Object.html)
* [XSD](xsd)
* [XSD::XMLParser](xsd/xmlparser)
* [XSD::XMLParser::Nokogiri](xsd/xmlparser/nokogiri)



 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/table_of_contents.html>

module Nokogiri
================

  [`Nokogiri`](nokogiri) parses and searches XML/HTML very quickly, and also has correctly implemented CSS3 selector support as well as XPath 1.0 support.

 Parsing a document returns either a [`Nokogiri::XML::Document`](nokogiri/xml/document), or a [`Nokogiri::HTML4::Document`](nokogiri/html4/document) depending on the kind of document you parse.

 Here is an example:

 
```
require 'nokogiri'
require 'open-uri'

# Get a Nokogiri::HTML4::Document for the page we’re interested in...

doc = Nokogiri::HTML4(URI.open('http://www.google.com/search?q=tenderlove'))

# Do funky things with it using Nokogiri::XML::Node methods...

####
# Search for nodes by css
doc.css('h3.r a.l').each do |link|
  puts link.content
end

```
 See also:

 * [`Nokogiri::XML::Searchable#css`](nokogiri/xml/searchable#method-i-css) for more information about [`CSS`](nokogiri/css) searching
* [`Nokogiri::XML::Searchable#xpath`](nokogiri/xml/searchable#method-i-xpath) for more information about XPath searching

     ### Constants

   HTML   Alias for [`Nokogiri::HTML4`](nokogiri/html4)

  JAR\_DEPENDENCIES   generated by the :vendor\_jars rake task

  NEKO\_VERSION  VERSION   The version of [`Nokogiri`](nokogiri) you are using

  XERCES\_VERSION      ### Public Class Methods

      HTML(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) → Nokogiri::HTML4::Document  Show source   
 
```
# File lib/nokogiri/html.rb, line 10
  
```
  Parse [`HTML`](nokogiri/html4). Convenience method for [`Nokogiri::HTML4::Document.parse`](nokogiri/html4/document#method-c-parse)

       HTML4(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) → Nokogiri::HTML4::Document  Show source   
 
```
# File lib/nokogiri/html4.rb, line 10
def HTML4(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block)
  Nokogiri::HTML4::Document.parse(input, url, encoding, options, &block)
end
```
  Parse [`HTML`](nokogiri/html4). Convenience method for [`Nokogiri::HTML4::Document.parse`](nokogiri/html4/document#method-c-parse)

      HTML5(input, url = nil, encoding = nil, \*\*options, &block) Show source   
 
```
# File lib/nokogiri/html5.rb, line 30
def self.HTML5(input, url = nil, encoding = nil, **options, &block)
  Nokogiri::HTML5::Document.parse(input, url, encoding, **options, &block)
end
```
  Since v1.12.0

 ⚠ [`HTML5`](nokogiri/html5) functionality is not available when running JRuby.

 Parse an [`HTML5`](nokogiri/html5) document. Convenience method for {Nokogiri::HTML5::Document.parse}

      Slop(\*args, &block) Show source   
 
```
# File lib/nokogiri.rb, line 83
def Slop(*args, &block)
  Nokogiri(*args, &block).slop!
end
```
  Parse a document and add the [`Slop`](nokogiri#method-c-Slop) decorator. The [`Slop`](nokogiri#method-c-Slop) decorator implements method\_missing such that methods may be used instead of [`CSS`](nokogiri/css) or XPath. For example:

 
```
doc = Nokogiri::Slop(<<-eohtml)
  <html>
    <body>
      <p>first</p>
      <p>second</p>
    </body>
  </html>
eohtml
assert_equal('second', doc.html.body.p[1].text)

```
      XML(thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_XML, &block) Show source   
 
```
# File lib/nokogiri/xml.rb, line 7
def XML(thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block)
  Nokogiri::XML::Document.parse(thing, url, encoding, options, &block)
end
```
  Parse [`XML`](nokogiri/xml). Convenience method for [`Nokogiri::XML::Document.parse`](nokogiri/xml/document#method-c-parse)

      XSLT(stylesheet, modules = {}) Show source   
 
```
# File lib/nokogiri/xslt.rb, line 13
def XSLT(stylesheet, modules = {})
  XSLT.parse(stylesheet, modules)
end
```
  Create a [`Nokogiri::XSLT::Stylesheet`](nokogiri/xslt/stylesheet) with `stylesheet`.

 Example:

 
```
xslt = Nokogiri::XSLT(File.read(ARGV[0]))

```
      make(input = nil, opts = {}, &blk) Show source   
 
```
# File lib/nokogiri.rb, line 60
def make(input = nil, opts = {}, &blk)
  if input
    Nokogiri::HTML4.fragment(input).children.first
  else
    Nokogiri(&blk)
  end
end
```
  Create a new [`Nokogiri::XML::DocumentFragment`](nokogiri/xml/documentfragment)

      parse(string, url = nil, encoding = nil, options = nil) { |doc| ... } Show source   
 
```
# File lib/nokogiri.rb, line 42
def parse(string, url = nil, encoding = nil, options = nil)
  if string.respond_to?(:read) ||
      /^\s*<(?:!DOCTYPE\s+)?html[\s>]/i.match?(string[0, 512])
    # Expect an HTML indicator to appear within the first 512
    # characters of a document. (<?xml ?> + <?xml-stylesheet ?>
    # shouldn't be that long)
    Nokogiri.HTML4(string, url, encoding,
      options || XML::ParseOptions::DEFAULT_HTML)
  else
    Nokogiri.XML(string, url, encoding,
      options || XML::ParseOptions::DEFAULT_XML)
  end.tap do |doc|
    yield doc if block_given?
  end
end
```
  Parse an [`HTML`](nokogiri/html4) or [`XML`](nokogiri/xml) document. `string` contains the document.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri.html>

module Nokogiri::CSS
=====================

  Translate a [`CSS`](css) selector into an XPath 1.0 query

     ### Public Class Methods

      xpath\_for(selector) → String  Show source    xpath\_for(selector [, prefix:] [, visitor:] [, ns:]) → String    
 
```
# File lib/nokogiri/css.rb, line 42
def xpath_for(selector, options = {})
  raise TypeError, "no implicit conversion of #{selector.inspect} to String" unless selector.respond_to?(:to_str)

  selector = selector.to_str
  raise Nokogiri::CSS::SyntaxError, "empty CSS selector" if selector.empty?

  prefix = options.fetch(:prefix, Nokogiri::XML::XPath::GLOBAL_SEARCH_PREFIX)
  visitor = options.fetch(:visitor) { Nokogiri::CSS::XPathVisitor.new }
  ns = options.fetch(:ns, {})

  Parser.new(ns).xpath_for(selector, prefix, visitor)
end
```
  Translate a [`CSS`](css) selector to the equivalent XPath query.

  Parameters   * `selector` (String) The [`CSS`](css) selector to be translated into XPath
* `prefix:` (String)

 The XPath prefix for the query, see [`Nokogiri::XML::XPath`](xml/xpath) for some options. Default is `XML::XPath::GLOBAL_SEARCH_PREFIX`.
* `visitor:` ([`Nokogiri::CSS::XPathVisitor`](css/xpathvisitor))

 The visitor class to use to transform the AST into XPath. Default is `Nokogiri::CSS::XPathVisitor.new`.
* `ns:` (Hash<String ⇒ String>)

 The namespaces that are referenced in the query, if any. This is a hash where the keys are the namespace prefix and the values are the namespace URIs. Default is an empty Hash.

  Returns   (String) The equivalent XPath query for `selector`

   💡 Note that translated queries are cached for performance concerns.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/CSS.html>

module Nokogiri::CSS::XPathVisitor::BuiltinsConfig
===================================================

  Enum to direct [`XPathVisitor`](../xpathvisitor) when to use [`Nokogiri`](../../../nokogiri) builtin XPath functions.

     ### Constants

   ALWAYS   Always use [`Nokogiri`](../../../nokogiri) builtin functions whenever possible. This is probably only useful for testing.

  NEVER   Never use [`Nokogiri`](../../../nokogiri) builtin functions, always generate vanilla XPath 1.0 queries. This is the default when calling [`Nokogiri::CSS.xpath_for`](../../css#method-c-xpath_for) directly.

  OPTIMAL   Only use [`Nokogiri`](../../../nokogiri) builtin functions when they will be faster than vanilla XPath. This is the behavior chosen when searching for [`CSS`](../../css) selectors on a [`Nokogiri`](../../../nokogiri) document, fragment, or node.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/CSS/XPathVisitor/BuiltinsConfig.html>

module Nokogiri::CSS::XPathVisitor::DoctypeConfig
==================================================

  Enum to direct [`XPathVisitor`](../xpathvisitor) when to tweak the XPath query to suit the nature of the document being searched. Note that searches for [`CSS`](../../css) selectors from a [`Nokogiri`](../../../nokogiri) document, fragment, or node will choose the correct option automatically.

     ### Constants

   HTML4   The document being searched is an [`HTML4`](../../html4) document.

  HTML5   The document being searched is an [`HTML5`](../../html5) document.

  XML   The document being searched is an [`XML`](../../xml) document. This is the default.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/CSS/XPathVisitor/DoctypeConfig.html>

module Nokogiri::ClassResolver
===============================

  Some classes in [`Nokogiri`](../nokogiri) are namespaced as a group, for example Document, DocumentFragment, and Builder.

 It’s sometimes necessary to look up the related class, e.g.:

 
```
XML::Builder → XML::Document
HTML4::Builder → HTML4::Document
HTML5::Document → HTML5::DocumentFragment

```
 This module is included into those key classes who need to do this.

     ### Constants

   VALID\_NAMESPACES   [`related_class`](classresolver#method-i-related_class) restricts matching namespaces to those matching this set.

      ### Public Instance Methods

      related\_class(class\_name) → Class  Show source   
 
```
# File lib/nokogiri/class_resolver.rb, line 46
def related_class(class_name)
  klass = nil
  inspecting = self.class

  while inspecting
    namespace_path = inspecting.name.split("::")[0..-2]
    inspecting = inspecting.superclass

    next unless VALID_NAMESPACES.include?(namespace_path.last)

    related_class_name = (namespace_path << class_name).join("::")
    klass = begin
      Object.const_get(related_class_name)
    rescue NameError
      nil
    end
    break if klass
  end
  klass
end
```
  Find a class constant within the

 Some examples:

 
```
Nokogiri::XML::Document.new.related_class("DocumentFragment")
# => Nokogiri::XML::DocumentFragment
Nokogiri::HTML4::Document.new.related_class("DocumentFragment")
# => Nokogiri::HTML4::DocumentFragment

```
 Note this will also work for subclasses that follow the same convention, e.g.:

 
```
Loofah::HTML::Document.new.related_class("DocumentFragment")
# => Loofah::HTML::DocumentFragment

```
 And even if it’s a subclass, this will iterate through the superclasses:

 
```
class ThisIsATopLevelClass < Nokogiri::HTML4::Builder ; end
ThisIsATopLevelClass.new.related_class("Document")
# => Nokogiri::HTML4::Document

```
    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/ClassResolver.html>

class Nokogiri::EncodingHandler
================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
    ### Constants

   USEFUL\_ALIASES   Popular encoding aliases not known by all iconv implementations that [`Nokogiri`](../nokogiri) should support.

      ### Public Class Methods

      Nokogiri::EncodingHandler.[](name)  Show source   
 
```
static VALUE
rb_xml_encoding_handler_s_get(VALUE klass, VALUE key)
{
  xmlCharEncodingHandlerPtr handler;

  handler = xmlFindCharEncodingHandler(StringValueCStr(key));
  if (handler) {
    return Data_Wrap_Struct(klass, NULL, _xml_encoding_handler_dealloc, handler);
  }

  return Qnil;
}
```
  Get the encoding handler for `name`

       Nokogiri::EncodingHandler.alias(real\_name, alias\_name)  Show source   
 
```
static VALUE
rb_xml_encoding_handler_s_alias(VALUE klass, VALUE from, VALUE to)
{
  xmlAddEncodingAlias(StringValueCStr(from), StringValueCStr(to));

  return to;
}
```
  Alias encoding handler with name `real_name` to name `alias_name`

       Nokogiri::EncodingHandler.clear\_aliases!  Show source   
 
```
static VALUE
rb_xml_encoding_handler_s_clear_aliases(VALUE klass)
{
  xmlCleanupEncodingAliases();

  return klass;
}
```
  Remove all encoding aliases.

       Nokogiri::EncodingHandler.delete(name)  Show source   
 
```
static VALUE
rb_xml_encoding_handler_s_delete(VALUE klass, VALUE name)
{
  if (xmlDelEncodingAlias(StringValueCStr(name))) { return Qnil; }

  return Qtrue;
}
```
  Delete the encoding alias named `name`

      install\_default\_aliases() Show source   
 
```
# File lib/nokogiri/encoding_handler.rb, line 15
def install_default_aliases
  USEFUL_ALIASES.each do |alias_name, name|
    EncodingHandler.alias(name, alias_name) if EncodingHandler[alias_name].nil?
  end
end
```
       ### Public Instance Methods

      name  Show source   
 
```
static VALUE
rb_xml_encoding_handler_name(VALUE self)
{
  xmlCharEncodingHandlerPtr handler;

  Data_Get_Struct(self, xmlCharEncodingHandler, handler);

  return NOKOGIRI_STR_NEW2(handler->name);
}
```
  Get the name of this [`EncodingHandler`](encodinghandler)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/EncodingHandler.html>

module Nokogiri::Gumbo
=======================

    ### Constants

   DEFAULT\_MAX\_ATTRIBUTES   The default maximum number of attributes per element.

  DEFAULT\_MAX\_ERRORS   The default maximum number of errors for parsing a document or a fragment.

  DEFAULT\_MAX\_TREE\_DEPTH   The default maximum depth of the DOM tree produced by parsing a document or fragment.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/Gumbo.html>

class Nokogiri::CSS::SyntaxError
=================================



Parent:
[Nokogiri::SyntaxError](../syntaxerror)
 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/CSS/SyntaxError.html>

class Nokogiri::CSS::XPathVisitor
==================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  When translating [`CSS`](../css) selectors to XPath queries with [`Nokogiri::CSS.xpath_for`](../css#method-c-xpath_for), the [`XPathVisitor`](xpathvisitor) class allows for changing some of the behaviors related to builtin xpath functions and quirks of [`HTML5`](../html5).

     ### Public Class Methods

      new() → XPathVisitor  Show source    new(builtins:, doctype:) → XPathVisitor    
 
```
# File lib/nokogiri/css/xpath_visitor.rb, line 57
def initialize(builtins: BuiltinsConfig::NEVER, doctype: DoctypeConfig::XML)
  unless BuiltinsConfig::VALUES.include?(builtins)
    raise(ArgumentError, "Invalid values #{builtins.inspect} for builtins: keyword parameter")
  end
  unless DoctypeConfig::VALUES.include?(doctype)
    raise(ArgumentError, "Invalid values #{doctype.inspect} for doctype: keyword parameter")
  end

  @builtins = builtins
  @doctype = doctype
end
```
   Parameters   * `builtins:` ([`BuiltinsConfig`](xpathvisitor/builtinsconfig)) Determine when to use Nokogiri’s built-in xpath functions for performance improvements.
* `doctype:` ([`DoctypeConfig`](xpathvisitor/doctypeconfig)) Make document-type-specific accommodations for [`CSS`](../css) queries.

  Returns   [`XPathVisitor`](xpathvisitor)

        ### Public Instance Methods

      config() → Hash  Show source   
 
```
# File lib/nokogiri/css/xpath_visitor.rb, line 74
def config
  { builtins: @builtins, doctype: @doctype }
end
```
   Returns   a Hash representing the configuration of the [`XPathVisitor`](xpathvisitor), suitable for use as part of the [`CSS`](../css) cache key.

      

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/CSS/XPathVisitor.html>

module Nokogiri::Decorators
============================

 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/Decorators.html>

module Nokogiri::Decorators::Slop
==================================

  The [`Slop`](slop) decorator implements method missing such that a methods may be used instead of XPath or [`CSS`](../css). See [`Nokogiri.Slop`](../../nokogiri#method-c-Slop)

     ### Constants

   XPATH\_PREFIX   The default XPath search context for [`Slop`](slop)

      ### Public Instance Methods

     method\_missing(name, \*args, &block) Show source   
 
```
# File lib/nokogiri/decorators/slop.rb, line 14
def method_missing(name, *args, &block)
  if args.empty?
    list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, "")}")
  elsif args.first.is_a?(Hash)
    hash = args.first
    if hash[:css]
      list = css("#{name}#{hash[:css]}")
    elsif hash[:xpath]
      conds = Array(hash[:xpath]).join(" and ")
      list = xpath("#{XPATH_PREFIX}#{name}[#{conds}]")
    end
  else
    CSS::Parser.without_cache do
      list = xpath(
        *CSS.xpath_for("#{name}#{args.first}", prefix: XPATH_PREFIX),
      )
    end
  end

  super if list.empty?
  list.length == 1 ? list.first : list
end
```
  look for node with `name`. See [`Nokogiri.Slop`](../../nokogiri#method-c-Slop)

  Calls superclass method       respond\_to\_missing?(name, include\_private = false) Show source   
 
```
# File lib/nokogiri/decorators/slop.rb, line 37
def respond_to_missing?(name, include_private = false)
  list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, "")}")

  !list.empty?
end
```
     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/Decorators/Slop.html>

module Nokogiri::HTML4
=======================

  💡 This module/namespace is an alias for [`Nokogiri::HTML4`](html4) as of v1.12.0. Before v1.12.0,

 
```
Nokogiri::HTML4 did not exist, and this was the module/namespace for all HTML-related
classes.
```
 Since v1.12.0

 💡 Before v1.12.0, [`Nokogiri::HTML4`](html4) did not exist, and [`Nokogiri::HTML`](html4) was the module/namespace for parsing [`HTML`](html4).

     ### Constants

   NamedCharacters   Instance of [`Nokogiri::HTML4::EntityLookup`](html4/entitylookup)

      ### Public Class Methods

     fragment(string, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) Show source   
 
```
# File lib/nokogiri/html4.rb, line 29
def fragment(string, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block)
  HTML4::DocumentFragment.parse(string, encoding, options, &block)
end
```
  Parse a fragment from `string` in to a NodeSet.

      parse(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) Show source   
 
```
# File lib/nokogiri/html4.rb, line 23
def parse(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block)
  Document.parse(input, url, encoding, options, &block)
end
```
  Parse [`HTML`](html4). Convenience method for [`Nokogiri::HTML4::Document.parse`](html4/document#method-c-parse)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4.html>

class Nokogiri::HTML4::Builder
===============================



Parent:
[Nokogiri::XML::Builder](../xml/builder)
  [`Nokogiri`](../../nokogiri) [`HTML`](../html4) builder is used for building [`HTML`](../html4) documents. It is very similar to the [`Nokogiri::XML::Builder`](../xml/builder). In fact, you should go read the documentation for [`Nokogiri::XML::Builder`](../xml/builder) before reading this documentation.

 Synopsis:
---------

 Create an [`HTML`](../html4) document with a body that has an onload attribute, and a span tag with a class of “bold” that has content of “Hello world”.

 
```
builder = Nokogiri::HTML4::Builder.new do |doc|
  doc.html {
    doc.body(:onload => 'some_func();') {
      doc.span.bold {
        doc.text "Hello world"
      }
    }
  }
end
puts builder.to_html

```
 The [`HTML`](../html4) builder inherits from the [`XML`](../xml) builder, so make sure to read the [`Nokogiri::XML::Builder`](../xml/builder) documentation.

     ### Public Instance Methods

     to\_html() Show source   
 
```
# File lib/nokogiri/html4/builder.rb, line 32
def to_html
  @doc.to_html
end
```
  Convert the builder to [`HTML`](../html4)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/Builder.html>

class Nokogiri::HTML4::Document
================================



Parent:
[Nokogiri::XML::Document](../xml/document)
    ### Public Class Methods

     parse(string\_or\_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML) { |options| ... } Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 172
def parse(string_or_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML)
  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil

  if string_or_io.respond_to?(:encoding)
    unless string_or_io.encoding == Encoding::ASCII_8BIT
      encoding ||= string_or_io.encoding.name
    end
  end

  if string_or_io.respond_to?(:read)
    if string_or_io.is_a?(Pathname)
      # resolve the Pathname to the file and open it as an IO object, see #2110
      string_or_io = string_or_io.expand_path.open
      url ||= string_or_io.path
    end

    unless encoding
      string_or_io = EncodingReader.new(string_or_io)
      begin
        return read_io(string_or_io, url, encoding, options.to_i)
      rescue EncodingReader::EncodingFound => e
        encoding = e.found_encoding
      end
    end
    return read_io(string_or_io, url, encoding, options.to_i)
  end

  # read_memory pukes on empty docs
  if string_or_io.nil? || string_or_io.empty?
    return encoding ? new.tap { |i| i.encoding = encoding } : new
  end

  encoding ||= EncodingReader.detect_encoding(string_or_io)

  read_memory(string_or_io, url, encoding, options.to_i)
end
```
  Parse [`HTML`](../html4). `string_or_io` may be a String, or any object that responds to *read* and *close* such as an IO, or StringIO. `url` is resource where this document is located. `encoding` is the encoding that should be used when processing the document. `options` is a number that sets options in the parser, such as Nokogiri::XML::ParseOptions::RECOVER. See the constants in [`Nokogiri::XML::ParseOptions`](../xml/parseoptions).

      ### Public Instance Methods

     fragment(tags = nil) Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 149
def fragment(tags = nil)
  DocumentFragment.new(self, tags, root)
end
```
  Create a [`Nokogiri::XML::DocumentFragment`](../xml/documentfragment) from `tags`

      meta\_encoding() Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 12
def meta_encoding
  if (meta = at_xpath("//meta[@charset]"))
    meta[:charset]
  elsif (meta = meta_content_type)
    meta["content"][/charset\s*=\s*([\w-]+)/i, 1]
  end
end
```
  Get the meta tag encoding for this document. If there is no meta tag, then nil is returned.

      meta\_encoding=(encoding) Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 36
def meta_encoding=(encoding)
  if (meta = meta_content_type)
    meta["content"] = format("text/html; charset=%s", encoding)
    encoding
  elsif (meta = at_xpath("//meta[@charset]"))
    meta["charset"] = encoding
  else
    meta = XML::Node.new("meta", self)
    if (dtd = internal_subset) && dtd.html5_dtd?
      meta["charset"] = encoding
    else
      meta["http-equiv"] = "Content-Type"
      meta["content"] = format("text/html; charset=%s", encoding)
    end

    if (head = at_xpath("//head"))
      head.prepend_child(meta)
    else
      set_metadata_element(meta)
    end
    encoding
  end
end
```
  Set the meta tag encoding for this document.

 If an meta encoding tag is already present, its content is replaced with the given text.

 Otherwise, this method tries to create one at an appropriate place supplying head and/or html elements as necessary, which is inside a head element if any, and before any text node or content element (typically <body>) if any.

 The result when trying to set an encoding that is different from the document encoding is undefined.

 Beware in CRuby, that libxml2 automatically inserts a meta tag into a head element.

      serialize(options = {}) Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 142
def serialize(options = {})
  options[:save_with] ||= XML::Node::SaveOptions::DEFAULT_HTML
  super
end
```
  Serialize Node using `options`. Save options can also be set using a block.

 See also [`Nokogiri::XML::Node::SaveOptions`](../xml/node/saveoptions) and Node.

 These two statements are equivalent:

 
```
node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)

```
 or

 
```
node.serialize(:encoding => 'UTF-8') do |config|
  config.format.as_xml
end

```
  Calls superclass method       title() Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 70
def title
  (title = at_xpath("//title")) && title.inner_text
end
```
  Get the title string of this document. Return nil if there is no title tag.

      title=(text) Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 85
def title=(text)
  tnode = XML::Text.new(text, self)
  if (title = at_xpath("//title"))
    title.children = tnode
    return text
  end

  title = XML::Node.new("title", self) << tnode
  if (head = at_xpath("//head"))
    head << title
  elsif (meta = (at_xpath("//meta[@charset]") || meta_content_type))
    # better put after charset declaration
    meta.add_next_sibling(title)
  else
    set_metadata_element(title)
  end
end
```
  Set the title string of this document.

 If a title element is already present, its content is replaced with the given text.

 Otherwise, this method tries to create one at an appropriate place supplying head and/or html elements as necessary, which is inside a head element if any, right after a meta encoding/charset tag if any, and before any text node or content element (typically <body>) if any.

       xpath\_doctype() → Nokogiri::CSS::XPathVisitor::DoctypeConfig  Show source   
 
```
# File lib/nokogiri/html4/document.rb, line 159
def xpath_doctype
  Nokogiri::CSS::XPathVisitor::DoctypeConfig::HTML4
end
```
   Returns   The document type which determines CSS-to-XPath translation.

   See XPathVisitor for more information.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/Document.html>

class Nokogiri::HTML4::DocumentFragment
========================================



Parent:
[Nokogiri::XML::DocumentFragment](../xml/documentfragment)
    ### Public Class Methods

     new(document, tags = nil, ctx = nil, options = XML::ParseOptions::DEFAULT\_HTML) { |options| ... } Show source   
 
```
# File lib/nokogiri/html4/document_fragment.rb, line 27
def initialize(document, tags = nil, ctx = nil, options = XML::ParseOptions::DEFAULT_HTML)
  return self unless tags

  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  if ctx
    preexisting_errors = document.errors.dup
    node_set = ctx.parse("<div>#{tags}</div>", options)
    node_set.first.children.each { |child| child.parent = self } unless node_set.empty?
    self.errors = document.errors - preexisting_errors
  else
    # This is a horrible hack, but I don't care
    path = if /^\s*?<body/i.match?(tags)
      "/html/body"
    else
      "/html/body/node()"
    end

    temp_doc = HTML4::Document.parse("<html><body>#{tags}", nil, document.encoding, options)
    temp_doc.xpath(path).each { |child| child.parent = self }
    self.errors = temp_doc.errors
  end
  children
end
```
       parse(tags, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) Show source   
 
```
# File lib/nokogiri/html4/document_fragment.rb, line 8
def self.parse(tags, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block)
  doc = HTML4::Document.new

  encoding ||= if tags.respond_to?(:encoding)
    encoding = tags.encoding
    if encoding == ::Encoding::ASCII_8BIT
      "UTF-8"
    else
      encoding.name
    end
  else
    "UTF-8"
  end

  doc.encoding = encoding

  new(doc, tags, nil, options, &block)
end
```
  Create a [`Nokogiri::XML::DocumentFragment`](../xml/documentfragment) from `tags`, using `encoding`

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/DocumentFragment.html>

class Nokogiri::HTML4::ElementDescription
==========================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
    ### Constants

   ACTION\_ATTR  ALIGN\_ATTR  ALT\_ATTR  APPLET\_ATTRS  AREA\_ATTRS  ATTRS  A\_ATTRS  BASEFONT\_ATTRS  BGCOLOR\_ATTR  BLOCK  BLOCKLI\_ELT  BODY\_ATTRS  BODY\_CONTENTS  BODY\_DEPR  BUTTON\_ATTRS  CELLHALIGN  CELLVALIGN  CLEAR\_ATTRS  COL\_ATTRS  COL\_ELT  COMPACT\_ATTR  COMPACT\_ATTRS  CONTENT\_ATTR  COREATTRS  CORE\_ATTRS  CORE\_I18N\_ATTRS  DIR\_ATTR  DL\_CONTENTS  DefaultDescriptions   This is filled in down below.

  Desc   Methods are defined protected by method\_defined? because at this point the C-library or Java library is already loaded, and we don’t want to clobber any methods that have been defined there.

  EDIT\_ATTRS  EMBED\_ATTRS  EMPTY  EVENTS  FIELDSET\_CONTENTS  FLOW  FLOW\_PARAM  FONTSTYLE   Attributes defined and categorized

  FONT\_ATTRS  FORMCTRL  FORM\_ATTRS  FORM\_CONTENTS  FRAMESET\_ATTRS  FRAMESET\_CONTENTS  FRAME\_ATTRS  HEADING  HEAD\_ATTRS  HEAD\_CONTENTS  HREF\_ATTRS  HR\_DEPR  HTML\_ATTRS  HTML\_CDATA  HTML\_CONTENT  HTML\_FLOW  HTML\_INLINE  HTML\_PCDATA  I18N  I18N\_ATTRS  IFRAME\_ATTRS  IMG\_ATTRS  INLINE  INLINE\_P  INPUT\_ATTRS  LABEL\_ATTR  LABEL\_ATTRS  LANGUAGE\_ATTR  LEGEND\_ATTRS  LINK\_ATTRS  LIST  LI\_ELT  MAP\_CONTENTS  META\_ATTRS  MODIFIER  NAME\_ATTR  NOFRAMES\_CONTENT  OBJECT\_ATTRS  OBJECT\_CONTENTS  OBJECT\_DEPR  OL\_ATTRS  OPTGROUP\_ATTRS  OPTION\_ATTRS  OPTION\_ELT  PARAM\_ATTRS  PCDATA  PHRASE  PRE\_CONTENT  PROMPT\_ATTRS  QUOTE\_ATTRS  ROWS\_COLS\_ATTR  SCRIPT\_ATTRS  SELECT\_ATTRS  SELECT\_CONTENT  SPECIAL  SRC\_ALT\_ATTRS  STYLE\_ATTRS  TABLE\_ATTRS  TABLE\_CONTENTS  TABLE\_DEPR  TALIGN\_ATTRS  TARGET\_ATTR  TEXTAREA\_ATTRS  TH\_TD\_ATTR  TH\_TD\_DEPR  TR\_CONTENTS  TR\_ELT  TYPE\_ATTR  UL\_DEPR  VERSION\_ATTR  WIDTH\_ATTR      ### Public Instance Methods

     block?() Show source   
 
```
# File lib/nokogiri/html4/element_description.rb, line 8
def block?
  !inline?
end
```
  Is this element a block element?

      default\_sub\_element() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 57
def default_sub_element
  default_desc&.defaultsubelt
end
```
       deprecated?() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 45
def deprecated?
  default_desc&.depr
end
```
       deprecated\_attributes() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 70
def deprecated_attributes
  d = default_desc
  d ? d.attrs_depr : []
end
```
       description() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 51
def description
  default_desc&.desc
end
```
       implied\_end\_tag?() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 33
def implied_end_tag?
  default_desc&.endTag
end
```
       implied\_start\_tag?() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 27
def implied_start_tag?
  default_desc&.startTag
end
```
       inspect() Show source   
 
```
# File lib/nokogiri/html4/element_description.rb, line 20
def inspect
  "#<#{self.class.name}: #{name} #{description}>"
end
```
  Inspection information

      optional\_attributes() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 63
def optional_attributes
  d = default_desc
  d ? d.attrs_opt : []
end
```
       required\_attributes() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 77
def required_attributes
  d = default_desc
  d ? d.attrs_req : []
end
```
       save\_end\_tag?() Show source   
 
```
# File lib/nokogiri/html4/element_description_defaults.rb, line 39
def save_end_tag?
  default_desc&.saveEndTag
end
```
       to\_s() Show source   
 
```
# File lib/nokogiri/html4/element_description.rb, line 14
def to_s
  "#{name}: #{description}"
end
```
  Convert this description to a string

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/ElementDescription.html>

class Nokogiri::HTML4::EntityDescription
=========================================



Parent:
Struct.new(:value, :name, :description);
 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/EntityDescription.html>

class Nokogiri::HTML4::EntityLookup
====================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
    ### Public Instance Methods

     [](name) Show source   
 
```
# File lib/nokogiri/html4/entity_lookup.rb, line 10
def [](name)
  (val = get(name)) && val.value
end
```
  Look up entity with `name`

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/EntityLookup.html>

module Nokogiri::HTML4::SAX
============================

  [`Nokogiri`](../../nokogiri) lets you write a [`SAX`](sax) parser to process [`HTML`](../html4) but get [`HTML`](../html4) correction features.

 See [`Nokogiri::HTML4::SAX::Parser`](sax/parser) for a basic example of using a [`SAX`](sax) parser with [`HTML`](../html4).

 For more information on [`SAX`](sax) parsers, see [`Nokogiri::XML::SAX`](../xml/sax)

  

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/SAX.html>

class Nokogiri::HTML4::SAX::ParserContext
==========================================



Parent:
[Nokogiri::XML::SAX::ParserContext](../../xml/sax/parsercontext)
  💡 This class is an alias for [`Nokogiri::HTML4::SAX::ParserContext`](parsercontext) as of v1.12.0.

 Context for [`HTML`](../../html4) [`SAX`](../sax) parsers. This class is usually not instantiated by the user. Instead, you should be looking at [`Nokogiri::HTML4::SAX::Parser`](parser)

     ### Public Class Methods

     new(thing, encoding = "UTF-8") Show source   
 
```
# File lib/nokogiri/html4/sax/parser_context.rb, line 10
def self.new(thing, encoding = "UTF-8")
  if [:read, :close].all? { |x| thing.respond_to?(x) }
    super
  else
    memory(thing, encoding)
  end
end
```
   Calls superclass method [`Nokogiri::XML::SAX::ParserContext::new`](../../xml/sax/parsercontext#method-c-new)     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/SAX/ParserContext.html>

class Nokogiri::HTML4::SAX::Parser
===================================



Parent:
[Nokogiri::XML::SAX::Parser](../../xml/sax/parser)
  💡 This class is an alias for [`Nokogiri::HTML4::SAX::Parser`](parser) as of v1.12.0.

 This class lets you perform [`SAX`](../sax) style parsing on [`HTML`](../../html4) with [`HTML`](../../html4) error correction.

 Here is a basic usage example:

 
```
class MyDoc < Nokogiri::XML::SAX::Document
  def start_element name, attributes = []
    puts "found a #{name}"
  end
end

parser = Nokogiri::HTML4::SAX::Parser.new(MyDoc.new)
parser.parse(File.read(ARGV[0], mode: 'rb'))

```
 For more information on [`SAX`](../sax) parsers, see [`Nokogiri::XML::SAX`](../../xml/sax)

     ### Public Instance Methods

     parse\_file(filename, encoding = "UTF-8") { |ctx| ... } Show source   
 
```
# File lib/nokogiri/html4/sax/parser.rb, line 51
def parse_file(filename, encoding = "UTF-8")
  raise ArgumentError unless filename
  raise Errno::ENOENT unless File.exist?(filename)
  raise Errno::EISDIR if File.directory?(filename)

  ctx = ParserContext.file(filename, encoding)
  yield ctx if block_given?
  ctx.parse_with(self)
end
```
  Parse a file with `filename`

      parse\_io(io, encoding = "UTF-8") { |ctx| ... } Show source   
 
```
# File lib/nokogiri/html4/sax/parser.rb, line 41
def parse_io(io, encoding = "UTF-8")
  check_encoding(encoding)
  @encoding = encoding
  ctx = ParserContext.io(io, ENCODINGS[encoding])
  yield ctx if block_given?
  ctx.parse_with(self)
end
```
  Parse given `io`

      parse\_memory(data, encoding = "UTF-8") { |ctx| ... } Show source   
 
```
# File lib/nokogiri/html4/sax/parser.rb, line 30
def parse_memory(data, encoding = "UTF-8")
  raise TypeError unless String === data
  return if data.empty?

  ctx = ParserContext.memory(data, encoding)
  yield ctx if block_given?
  ctx.parse_with(self)
end
```
  Parse html stored in `data` using `encoding`

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/SAX/Parser.html>

class Nokogiri::HTML4::SAX::PushParser
=======================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  💡 This class is an alias for [`Nokogiri::HTML4::SAX::PushParser`](pushparser) as of v1.12.0.

     ### Attributes

    document[RW]   The Nokogiri::HTML4::SAX::Document on which the [`PushParser`](pushparser) will be operating

      ### Public Class Methods

     new(doc = HTML4::SAX::Document.new, file\_name = nil, encoding = "UTF-8") Show source   
 
```
# File lib/nokogiri/html4/sax/push_parser.rb, line 11
def initialize(doc = HTML4::SAX::Document.new, file_name = nil, encoding = "UTF-8")
  @document = doc
  @encoding = encoding
  @sax_parser = HTML4::SAX::Parser.new(doc, @encoding)

  ## Create our push parser context
  initialize_native(@sax_parser, file_name, encoding)
end
```
       ### Public Instance Methods

     <<(chunk, last\_chunk = false)    Alias for: [write](pushparser#method-i-write)      finish() Show source   
 
```
# File lib/nokogiri/html4/sax/push_parser.rb, line 31
def finish
  write("", true)
end
```
  Finish the parsing. This method is only necessary for Nokogiri::HTML4::SAX::Document#end\_document to be called.

      write(chunk, last\_chunk = false) Show source   
 
```
# File lib/nokogiri/html4/sax/push_parser.rb, line 23
def write(chunk, last_chunk = false)
  native_write(chunk, last_chunk)
end
```
  Write a `chunk` of [`HTML`](../../html4) to the [`PushParser`](pushparser). Any callback methods that can be called will be called immediately.

   Also aliased as: [<<](pushparser#method-i-3C-3C)    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML4/SAX/PushParser.html>

module Nokogiri::HTML5
=======================

  Usage
-----

 ⚠ [`HTML5`](html5) functionality is not available when running JRuby.

 Parse an [`HTML5`](html5) document:

 
```
doc = Nokogiri.HTML5(string)

```
 Parse an [`HTML5`](html5) fragment:

 
```
fragment = Nokogiri::HTML5.fragment(string)

```
 Parsing options
---------------

 The document and fragment parsing methods support options that are different from Nokogiri’s.

 * `Nokogiri.HTML5(html, url = nil, encoding = nil, options = {})`
* `Nokogiri::HTML5.parse(html, url = nil, encoding = nil, options = {})`
* `Nokogiri::HTML5::Document.parse(html, url = nil, encoding = nil, options = {})`
* `Nokogiri::HTML5.fragment(html, encoding = nil, options = {})`
* `Nokogiri::HTML5::DocumentFragment.parse(html, encoding = nil, options = {})`

 The three currently supported options are `:max_errors`, `:max_tree_depth` and `:max_attributes`, described below.

 ### Error reporting

 [`Nokogiri`](../nokogiri) contains an experimental [`HTML5`](html5) parse error reporting facility. By default, no parse errors are reported but this can be configured by passing the `:max_errors` option to {HTML5.parse} or {HTML5.fragment}.

 For example, this script:

 
```
doc = Nokogiri::HTML5.parse('<span/>Hi there!</span foo=bar />', max_errors: 10)
doc.errors.each do |err|
  puts(err)
end

```
 Emits:

 
```
1:1: ERROR: Expected a doctype token
<span/>Hi there!</span foo=bar />
^
1:1: ERROR: Start tag of nonvoid HTML element ends with '/>', use '>'.
<span/>Hi there!</span foo=bar />
^
1:17: ERROR: End tag ends with '/>', use '>'.
<span/>Hi there!</span foo=bar />
                ^
1:17: ERROR: End tag contains attributes.
<span/>Hi there!</span foo=bar />
                ^
```
 Using `max_errors: -1` results in an unlimited number of errors being returned.

 The errors returned by {HTML5::Document#errors} are instances of {Nokogiri::XML::SyntaxError}.

 The {[html.spec.whatwg.org/multipage/parsing.html#parse-errors](https://html.spec.whatwg.org/multipage/parsing.html#parse-errors) [`HTML`](html4) standard} defines a number of standard parse error codes. These error codes only cover the “tokenization” stage of parsing [`HTML`](html4). The parse errors in the “tree construction” stage do not have standardized error codes (yet).

 As a convenience to [`Nokogiri`](../nokogiri) users, the defined error codes are available via {Nokogiri::XML::SyntaxError#str1} method.

 
```
doc = Nokogiri::HTML5.parse('<span/>Hi there!</span foo=bar />', max_errors: 10)
doc.errors.each do |err|
  puts("#{err.line}:#{err.column}: #{err.str1}")
end
# => 1:1: generic-parser
#    1:1: non-void-html-element-start-tag-with-trailing-solidus
#    1:17: end-tag-with-trailing-solidus
#    1:17: end-tag-with-attributes

```
 Note that the first error is `generic-parser` because it’s an error from the tree construction stage and doesn’t have a standardized error code.

 For the purposes of semantic versioning, the error messages, error locations, and error codes are not part of Nokogiri’s public API. That is, these are subject to change without Nokogiri’s major version number changing. These may be stabilized in the future.

 ### Maximum tree depth

 The maximum depth of the DOM tree parsed by the various parsing methods is configurable by the `:max_tree_depth` option. If the depth of the tree would exceed this limit, then an {::ArgumentError} is thrown.

 This limit (which defaults to `Nokogiri::Gumbo::DEFAULT_MAX_TREE_DEPTH = 400`) can be removed by giving the option `max_tree_depth: -1`.

 
```
html = '<!DOCTYPE html>' + '<div>' * 1000
doc = Nokogiri.HTML5(html)
# raises ArgumentError: Document tree depth limit exceeded
doc = Nokogiri.HTML5(html, max_tree_depth: -1)

```
 ### Attribute limit per element

 The maximum number of attributes per DOM element is configurable by the `:max_attributes` option. If a given element would exceed this limit, then an {::ArgumentError} is thrown.

 This limit (which defaults to `Nokogiri::Gumbo::DEFAULT_MAX_ATTRIBUTES = 400`) can be removed by giving the option `max_attributes: -1`.

 
```
html = '<!DOCTYPE html><div ' + (1..1000).map { |x| "attr-#{x}" }.join(' ') + '>'
# "<!DOCTYPE html><div attr-1 attr-2 attr-3 ... attr-1000>"
doc = Nokogiri.HTML5(html)
# raises ArgumentError: Attributes per element limit exceeded
doc = Nokogiri.HTML5(html, max_attributes: -1)

```
  [`HTML`](html4) Serialization
------------------------------

 After parsing [`HTML`](html4), it may be serialized using any of the {Nokogiri::XML::Node} serialization methods. In particular, {XML::Node#serialize}, {XML::Node#to\_html}, and {XML::Node#to\_s} will serialize a given node and its children. (This is the equivalent of JavaScript’s `Element.outerHTML`.) Similarly, {XML::Node#inner\_html} will serialize the children of a given node. (This is the equivalent of JavaScript’s `Element.innerHTML`.)

 
```
doc = Nokogiri::HTML5("<!DOCTYPE html><span>Hello world!</span>")
puts doc.serialize
# => <!DOCTYPE html><html><head></head><body><span>Hello world!</span></body></html>

```
 Due to quirks in how [`HTML`](html4) is parsed and serialized, it’s possible for a DOM tree to be serialized and then re-parsed, resulting in a different DOM. Mostly, this happens with DOMs produced from invalid [`HTML`](html4). Unfortunately, even valid [`HTML`](html4) may not survive serialization and re-parsing.

 In particular, a newline at the start of `pre`, `listing`, and `textarea` elements is ignored by the parser.

 
```
doc = Nokogiri::HTML5(<<-EOF)
<!DOCTYPE html>
<pre>
Content</pre>
EOF
puts doc.at('/html/body/pre').serialize
# => <pre>Content</pre>

```
 In this case, the original [`HTML`](html4) is semantically equivalent to the serialized version. If the `pre`, `listing`, or `textarea` content starts with two newlines, the first newline will be stripped on the first parse and the second newline will be stripped on the second, leading to semantically different DOMs. Passing the parameter `preserve_newline: true` will cause two or more newlines to be preserved. (A single leading newline will still be removed.)

 
```
doc = Nokogiri::HTML5(<<-EOF)
<!DOCTYPE html>
<listing>

Content</listing>
EOF
puts doc.at('/html/body/listing').serialize(preserve_newline: true)
# => <listing>
#
#    Content</listing>

```
 Encodings
---------

 [`Nokogiri`](../nokogiri) always parses [`HTML5`](html5) using {[en.wikipedia.org/wiki/UTF-8](https://en.wikipedia.org/wiki/UTF-8) UTF-8}; however, the encoding of the input can be explicitly selected via the optional `encoding` parameter. This is most useful when the input comes not from a string but from an IO object.

 When serializing a document or node, the encoding of the output string can be specified via the `:encoding` options. Characters that cannot be encoded in the selected encoding will be encoded as {[en.wikipedia.org/wiki/List\_of\_XML\_and\_HTML\_character\_entity\_references](https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references) [`HTML`](html4) numeric entities}.

 
```
frag = Nokogiri::HTML5.fragment('<span>아는 길도 물어가라</span>')
html = frag.serialize(encoding: 'US-ASCII')
puts html
# => <span>&#xc544;&#xb294; &#xae38;&#xb3c4; &#xbb3c;&#xc5b4;&#xac00;&#xb77c;</span>
frag = Nokogiri::HTML5.fragment(html)
puts frag.serialize
# => <span>아는 길도 물어가라</span>

```
 (There’s a {[bugs.ruby-lang.org/issues/15033](https://bugs.ruby-lang.org/issues/15033) bug} in all current versions of Ruby that can cause the entity encoding to fail. Of the mandated supported encodings for [`HTML`](html4), the only encoding I’m aware of that has this bug is `'ISO-2022-JP'`. We recommend avoiding this encoding.)

 Notes
-----

 * The {Nokogiri::HTML5.fragment} function takes a string and parses it as a [`HTML5`](html5) document. The +<html>+, +<head>+, and +<body>+ elements are removed from this document, and any children of these elements that remain are returned as a {Nokogiri::HTML5::DocumentFragment}.
* The {Nokogiri::HTML5.parse} function takes a string and passes it to the `gumbo_parse_with_options` method, using the default options. The resulting [`Gumbo`](gumbo) parse tree is then walked.
* Instead of uppercase element names, lowercase element names are produced.
* Instead of returning `unknown` as the element name for unknown tags, the original tag name is returned verbatim.

 Since v1.12.0

     ### Public Class Methods

     fragment(string, encoding = nil, \*\*options) Show source   
 
```
# File lib/nokogiri/html5.rb, line 238
def fragment(string, encoding = nil, **options)
  DocumentFragment.parse(string, encoding, options)
end
```
  Parse a fragment from `string`. Convenience method for {Nokogiri::HTML5::DocumentFragment.parse}.

      get(uri, options = {}) Show source   
 
```
# File lib/nokogiri/html5.rb, line 249
def get(uri, options = {})
  # TODO: deprecate
  warn("Nokogiri::HTML5.get is deprecated and will be removed in a future version of Nokogiri.",
    uplevel: 1, category: :deprecated)
  get_impl(uri, options)
end
```
  Fetch and parse a [`HTML`](html4) document from the web, following redirects, handling https, and determining the character encoding using [`HTML5`](html5) rules. `uri` may be a `String` or a `URI`. `options` contains http headers and special options. Everything which is not a special option is considered a header. Special options include:

 
```
* :follow_limit => number of redirects which are followed
* :basic_auth => [username, password]
```
      parse(string, url = nil, encoding = nil, \*\*options, &block) Show source   
 
```
# File lib/nokogiri/html5.rb, line 232
def parse(string, url = nil, encoding = nil, **options, &block)
  Document.parse(string, url, encoding, **options, &block)
end
```
  Parse an [`HTML`](html4) 5 document. Convenience method for {Nokogiri::HTML5::Document.parse}

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML5.html>

class Nokogiri::HTML5::DocumentFragment
========================================



Parent:
[Nokogiri::HTML4::DocumentFragment](../html4/documentfragment)
  Since v1.12.0

 💡 [`HTML5`](../html5) functionality is not available when running JRuby.

     ### Attributes

    document[RW]     errors[RW]     quirks\_mode[R]   Get the parser’s quirks mode value. See [`HTML5::QuirksMode`](quirksmode).

 This method returns ‘nil` if the parser was not invoked (e.g., `Nokogiri::HTML5::DocumentFragment.new(doc)`).

 Since v1.14.0

      ### Public Class Methods

     new(doc, tags = nil, ctx = nil, options = {}) Show source   
 
```
# File lib/nokogiri/html5/document_fragment.rb, line 39
def initialize(doc, tags = nil, ctx = nil, options = {})
  self.document = doc
  self.errors = []
  return self unless tags

  max_attributes = options[:max_attributes] || Nokogiri::Gumbo::DEFAULT_MAX_ATTRIBUTES
  max_errors = options[:max_errors] || Nokogiri::Gumbo::DEFAULT_MAX_ERRORS
  max_depth = options[:max_tree_depth] || Nokogiri::Gumbo::DEFAULT_MAX_TREE_DEPTH
  tags = Nokogiri::HTML5.read_and_encode(tags, nil)
  Nokogiri::Gumbo.fragment(self, tags, ctx, max_attributes, max_errors, max_depth)
end
```
  Create a document fragment.

      parse(tags, encoding = nil, options = {}) Show source   
 
```
# File lib/nokogiri/html5/document_fragment.rb, line 58
def self.parse(tags, encoding = nil, options = {})
  doc = HTML5::Document.new
  tags = HTML5.read_and_encode(tags, encoding)
  doc.encoding = "UTF-8"
  new(doc, tags, nil, options)
end
```
  Parse a document fragment from `tags`, returning a Nodeset.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML5/DocumentFragment.html>

module Nokogiri::HTML5::Node
=============================

  Since v1.12.0

 💡 [`HTML5`](../html5) functionality is not available when running JRuby.

     ### Public Instance Methods

     fragment(tags) Show source   
 
```
# File lib/nokogiri/html5/node.rb, line 65
def fragment(tags)
  return super(tags) unless document.is_a?(HTML5::Document)

  DocumentFragment.new(document, tags, self)
end
```
   Calls superclass method       inner\_html(options = {}) Show source   
 
```
# File lib/nokogiri/html5/node.rb, line 28
def inner_html(options = {})
  return super(options) unless document.is_a?(HTML5::Document)

  result = options[:preserve_newline] && prepend_newline? ? +"\n" : +""
  result << children.map { |child| child.to_html(options) }.join
  result
end
```
   Calls superclass method       write\_to(io, \*options) { |config| ... } Show source   
 
```
# File lib/nokogiri/html5/node.rb, line 36
def write_to(io, *options)
  return super(io, *options) unless document.is_a?(HTML5::Document)

  options = options.first.is_a?(Hash) ? options.shift : {}
  encoding = options[:encoding] || options[0]
  if Nokogiri.jruby?
    save_options = options[:save_with] || options[1]
    indent_times = options[:indent] || 0
  else
    save_options = options[:save_with] || options[1] || XML::Node::SaveOptions::FORMAT
    indent_times = options[:indent] || 2
  end
  indent_string = (options[:indent_text] || " ") * indent_times

  config = XML::Node::SaveOptions.new(save_options.to_i)
  yield config if block_given?

  config_options = config.options
  if config_options & (XML::Node::SaveOptions::AS_XML | XML::Node::SaveOptions::AS_XHTML) != 0
    # Use Nokogiri's serializing code.
    native_write_to(io, encoding, indent_string, config_options)
  else
    # Serialize including the current node.
    html = html_standard_serialize(options[:preserve_newline] || false)
    encoding ||= document.encoding || Encoding::UTF_8
    io << html.encode(encoding, fallback: lambda { |c| "&#x#{c.ord.to_s(16)};" })
  end
end
```
   Calls superclass method     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML5/Node.html>

module Nokogiri::HTML5::QuirksMode
===================================

  Enum for the [`HTML5`](../html5) parser quirks mode values. Values returned by [`HTML5::Document#quirks_mode`](document#attribute-i-quirks_mode)

 See [dom.spec.whatwg.org/#concept-document-quirks](https://dom.spec.whatwg.org/#concept-document-quirks) for more information on [`HTML5`](../html5) quirks mode.

 Since v1.14.0

     ### Constants

   LIMITED\_QUIRKS  NO\_QUIRKS  QUIRKS    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML5/QuirksMode.html>

class Nokogiri::SyntaxError
============================



Parent:
StandardError
 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/SyntaxError.html>

class Nokogiri::XML::Comment
=============================



Parent:
cNokogiriXmlCharacterData
  [`Comment`](comment) represents a comment node in an xml document.

     ### Public Class Methods

      new(document\_or\_node, content)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  xmlNodePtr node;
  VALUE document;
  VALUE content;
  VALUE rest;
  VALUE rb_node;

  rb_scan_args(argc, argv, "2*", &document, &content, &rest);

  if (rb_obj_is_kind_of(document, cNokogiriXmlNode)) {
    document = rb_funcall(document, document_id, 0);
  } else if (!rb_obj_is_kind_of(document, cNokogiriXmlDocument)
             && !rb_obj_is_kind_of(document, cNokogiriXmlDocumentFragment)) {
    rb_raise(rb_eArgError, "first argument must be a XML::Document or XML::Node");
  }

  Data_Get_Struct(document, xmlDoc, xml_doc);

  node = xmlNewDocComment(
           xml_doc,
           (const xmlChar *)StringValueCStr(content)
         );

  rb_node = noko_xml_node_wrap(klass, node);
  rb_obj_call_init(rb_node, argc, argv);

  noko_xml_document_pin_node(node);

  if (rb_block_given_p()) { rb_yield(rb_node); }

  return rb_node;
}
```
  Create a new [`Comment`](comment) element on the `document` with `content`. Alternatively, if a `node` is passed, the `node`‘s document is used.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Comment.html>

class Nokogiri::HTML::Builder
==============================



Parent:
[Nokogiri::XML::Builder](../xml/builder)
  💡 This class is an alias for [`Nokogiri::HTML4::Builder`](../html4/builder) as of v1.12.0.

  

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML/Builder.html>

class Nokogiri::HTML::DocumentFragment
=======================================



Parent:
[Nokogiri::XML::DocumentFragment](../xml/documentfragment)
  💡 This class is an alias for [`Nokogiri::HTML4::DocumentFragment`](../html4/documentfragment) as of v1.12.0.

  

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML/DocumentFragment.html>

class Nokogiri::XML::CharacterData
===================================



Parent:
cNokogiriXmlNode
Included modules:
[Nokogiri::XML::PP::CharacterData](pp/characterdata)
 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/CharacterData.html>

class Nokogiri::HTML5::Document
================================



Parent:
[Nokogiri::HTML4::Document](../html4/document)
  Since v1.12.0

 💡 [`HTML5`](../html5) functionality is not available when running JRuby.

     ### Attributes

    quirks\_mode[R]   Get the parser’s quirks mode value. See [`HTML5::QuirksMode`](quirksmode).

 This method returns ‘nil` if the parser was not invoked (e.g., `Nokogiri::HTML5::Document.new`).

 Since v1.14.0

     url[R]   Get the url name for this document, as passed into [`Document.parse`](document#method-c-parse), [`Document.read_io`](document#method-c-read_io), or [`Document.read_memory`](document#method-c-read_memory)

      ### Public Class Methods

      parse(input)  Show source    parse(input, url=nil, encoding=nil, \*\*options)     parse(input, url=nil, encoding=nil) { |options| ... }    
 
```
# File lib/nokogiri/html5/document.rb, line 80
def parse(string_or_io, url = nil, encoding = nil, **options, &block)
  yield options if block
  string_or_io = "" unless string_or_io

  if string_or_io.respond_to?(:encoding) && string_or_io.encoding != Encoding::ASCII_8BIT
    encoding ||= string_or_io.encoding.name
  end

  if string_or_io.respond_to?(:read) && string_or_io.respond_to?(:path)
    url ||= string_or_io.path
  end
  unless string_or_io.respond_to?(:read) || string_or_io.respond_to?(:to_str)
    raise ArgumentError, "not a string or IO object"
  end

  do_parse(string_or_io, url, encoding, options)
end
```
  Parse [`HTML5`](../html5) input.

  Parameters   * `input` may be a String, or any object that responds to *read* and *close* such as an IO, or StringIO.
* `url` (optional) is a String indicating the canonical URI where this document is located.
* `encoding` (optional) is the encoding that should be used when processing the document.
* `options` (optional) is a configuration Hash (or keyword arguments) to set options during parsing. The three currently supported options are `:max_errors`, `:max_tree_depth` and `:max_attributes`, described at [`Nokogiri::HTML5`](../html5).

 ⚠ Note that these options are different than those made available by [`Nokogiri::XML::Document`](../xml/document) and [`Nokogiri::HTML4::Document`](../html4/document).
* `block` (optional) is passed a configuration Hash on which parse options may be set. See [`Nokogiri::HTML5`](../html5) for more information and usage.

  Returns   [`Nokogiri::HTML5::Document`](document)

        read\_io(io, url = nil, encoding = nil, \*\*options) Show source   
 
```
# File lib/nokogiri/html5/document.rb, line 101
def read_io(io, url = nil, encoding = nil, **options)
  raise ArgumentError, "io object doesn't respond to :read" unless io.respond_to?(:read)

  do_parse(io, url, encoding, options)
end
```
  Create a new document from an IO object.

 💡 Most users should prefer [`Document.parse`](document#method-c-parse) to this method.

      read\_memory(string, url = nil, encoding = nil, \*\*options) Show source   
 
```
# File lib/nokogiri/html5/document.rb, line 110
def read_memory(string, url = nil, encoding = nil, **options)
  raise ArgumentError, "string object doesn't respond to :to_str" unless string.respond_to?(:to_str)

  do_parse(string, url, encoding, options)
end
```
  Create a new document from a String.

 💡 Most users should prefer [`Document.parse`](document#method-c-parse) to this method.

      ### Public Instance Methods

      fragment() → Nokogiri::HTML5::DocumentFragment  Show source    fragment(markup) → Nokogiri::HTML5::DocumentFragment    
 
```
# File lib/nokogiri/html5/document.rb, line 147
def fragment(markup = nil)
  DocumentFragment.new(self, markup)
end
```
  Parse a [`HTML5`](../html5) document fragment from `markup`, returning a [`Nokogiri::HTML5::DocumentFragment`](documentfragment).

  Properties   * `markup` (String) The [`HTML5`](../html5) markup fragment to be parsed

  Returns   [`Nokogiri::HTML5::DocumentFragment`](documentfragment). This object’s children will be empty if ‘markup` is not passed, is empty, or is `nil`.

         xpath\_doctype() → Nokogiri::CSS::XPathVisitor::DoctypeConfig  Show source   
 
```
# File lib/nokogiri/html5/document.rb, line 163
def xpath_doctype
  Nokogiri::CSS::XPathVisitor::DoctypeConfig::HTML5
end
```
   Returns   The document type which determines CSS-to-XPath translation.

   See [`CSS::XPathVisitor`](../css/xpathvisitor) for more information.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML5/Document.html>

class Nokogiri::HTML::Document
===============================



Parent:
[Nokogiri::XML::Document](../xml/document)
  💡 This class is an alias for [`Nokogiri::HTML4::Document`](../html4/document) as of v1.12.0.

  

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/HTML/Document.html>

module Nokogiri::XML
=====================

    ### Constants

   XML\_C14N\_1\_0   Original C14N 1.0 spec canonicalization

  XML\_C14N\_1\_1   C14N 1.1 spec canonicalization

  XML\_C14N\_EXCLUSIVE\_1\_0   Exclusive C14N 1.0 spec canonicalization

      ### Public Class Methods

     Reader(string\_or\_io, url = nil, encoding = nil, options = ParseOptions::STRICT) { |options| ... } Show source   
 
```
# File lib/nokogiri/xml.rb, line 23
def Reader(string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT)
  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  if string_or_io.respond_to?(:read)
    return Reader.from_io(string_or_io, url, encoding, options.to_i)
  end

  Reader.from_memory(string_or_io, url, encoding, options.to_i)
end
```
  Parse an [`XML`](xml) document using the [`Nokogiri::XML::Reader`](xml/reader) API. See [`Nokogiri::XML::Reader`](xml/reader) for mor information

      RelaxNG(string\_or\_io, options = ParseOptions::DEFAULT\_SCHEMA) Show source   
 
```
# File lib/nokogiri/xml/relax_ng.rb, line 9
def RelaxNG(string_or_io, options = ParseOptions::DEFAULT_SCHEMA)
  RelaxNG.new(string_or_io, options)
end
```
  Create a new [`Nokogiri::XML::RelaxNG`](xml/relaxng) document from `string_or_io`. See [`Nokogiri::XML::RelaxNG`](xml/relaxng) for an example.

      Schema(string\_or\_io, options = ParseOptions::DEFAULT\_SCHEMA) Show source   
 
```
# File lib/nokogiri/xml/schema.rb, line 9
def Schema(string_or_io, options = ParseOptions::DEFAULT_SCHEMA)
  Schema.new(string_or_io, options)
end
```
  Create a new [`Nokogiri::XML::Schema`](xml/schema) object using a `string_or_io` object.

      fragment(string, options = ParseOptions::DEFAULT\_XML, &block) Show source   
 
```
# File lib/nokogiri/xml.rb, line 42
def fragment(string, options = ParseOptions::DEFAULT_XML, &block)
  XML::DocumentFragment.parse(string, options, &block)
end
```
  Parse a fragment from `string` in to a [`NodeSet`](xml/nodeset).

      parse(thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT\_XML, &block) Show source   
 
```
# File lib/nokogiri/xml.rb, line 36
def parse(thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block)
  Document.parse(thing, url, encoding, options, &block)
end
```
  Parse [`XML`](xml). Convenience method for [`Nokogiri::XML::Document.parse`](xml/document#method-c-parse)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML.html>

class Nokogiri::XML::Attr
==========================



Parent:
cNokogiriXmlNode
  [`Attr`](attr) represents a [`Attr`](attr) node in an xml document.

     ### Public Class Methods

      new(document, name)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  VALUE document;
  VALUE name;
  VALUE rest;
  xmlAttrPtr node;
  VALUE rb_node;

  rb_scan_args(argc, argv, "2*", &document, &name, &rest);

  if (! rb_obj_is_kind_of(document, cNokogiriXmlDocument)) {
    rb_raise(rb_eArgError, "parameter must be a Nokogiri::XML::Document");
  }

  Noko_Node_Get_Struct(document, xmlDoc, xml_doc);

  node = xmlNewDocProp(
           xml_doc,
           (const xmlChar *)StringValueCStr(name),
           NULL
         );

  noko_xml_document_pin_node((xmlNodePtr)node);

  rb_node = noko_xml_node_wrap(klass, (xmlNodePtr)node);
  rb_obj_call_init(rb_node, argc, argv);

  if (rb_block_given_p()) {
    rb_yield(rb_node);
  }

  return rb_node;
}
```
  Create a new [`Attr`](attr) element on the `document` with `name`

      ### Public Instance Methods

     content=(p1)    Alias for: [value=](attr#method-i-value-3D)       deconstruct\_keys(array\_of\_names) → Hash  Show source   
 
```
# File lib/nokogiri/xml/attr.rb, line 55
def deconstruct_keys(keys)
  { name: name, value: value, namespace: namespace }
end
```
  Returns a hash describing the [`Attr`](attr), to use in pattern matching.

 Valid keys and their values:

 * `name` → (String) The name of the attribute.
* `value` → (String) The value of the attribute.
* `namespace` → ([`Namespace`](namespace), nil) The [`Namespace`](namespace) of the attribute, or `nil` if there is no namespace.

 ⚡ This is an experimental feature, available since v1.14.0

 **Example**

 
```
doc = Nokogiri::XML.parse(<<~XML)
  <?xml version="1.0"?>
  <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko">
    <child1 foo="abc" noko:bar="def"/>
  </root>
XML

attributes = doc.root.elements.first.attribute_nodes
# => [#(Attr:0x35c { name = "foo", value = "abc" }),
#     #(Attr:0x370 {
#       name = "bar",
#       namespace = #(Namespace:0x384 {
#         prefix = "noko",
#         href = "http://nokogiri.org/ns/noko"
#         }),
#       value = "def"
#       })]

attributes.first.deconstruct_keys([:name, :value, :namespace])
# => {:name=>"foo", :value=>"abc", :namespace=>nil}

attributes.last.deconstruct_keys([:name, :value, :namespace])
# => {:name=>"bar",
#     :value=>"def",
#     :namespace=>
#      #(Namespace:0x384 {
#        prefix = "noko",
#        href = "http://nokogiri.org/ns/noko"
#        })}

```
       value=(content)  Show source   
 
```
static VALUE
set_value(VALUE self, VALUE content)
{
  xmlAttrPtr attr;
  xmlChar *value;
  xmlNode *cur;

  Noko_Node_Get_Struct(self, xmlAttr, attr);

  if (attr->children) {
    xmlFreeNodeList(attr->children);
  }
  attr->children = attr->last = NULL;

  if (content == Qnil) {
    return content;
  }

  value = xmlEncodeEntitiesReentrant(attr->doc, (unsigned char *)StringValueCStr(content));
  if (xmlStrlen(value) == 0) {
    attr->children = xmlNewDocText(attr->doc, value);
  } else {
    attr->children = xmlStringGetNodeList(attr->doc, value);
  }
  xmlFree(value);

  for (cur = attr->children; cur; cur = cur->next) {
    cur->parent = (xmlNode *)attr;
    cur->doc = attr->doc;
    if (cur->next == NULL) {
      attr->last = cur;
    }
  }

  return content;
}
```
  Set the value for this [`Attr`](attr) to `content`. Use ‘nil` to remove the value (e.g., a [`HTML`](../html4) boolean attribute).

   Also aliased as: [content=](attr#method-i-content-3D)    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Attr.html>

class Nokogiri::XML::AttributeDecl
===================================



Parent:
cNokogiriXmlNode
  Represents an attribute declaration in a [`DTD`](dtd)

     ### Public Instance Methods

      attribute\_type  Show source   
 
```
static VALUE
attribute_type(VALUE self)
{
  xmlAttributePtr node;
  Noko_Node_Get_Struct(self, xmlAttribute, node);
  return INT2NUM(node->atype);
}
```
  The [`attribute_type`](attributedecl#method-i-attribute_type) for this [`AttributeDecl`](attributedecl)

       default  Show source   
 
```
static VALUE
default_value(VALUE self)
{
  xmlAttributePtr node;
  Noko_Node_Get_Struct(self, xmlAttribute, node);

  if (node->defaultValue) { return NOKOGIRI_STR_NEW2(node->defaultValue); }
  return Qnil;
}
```
  The default value

       enumeration  Show source   
 
```
static VALUE
enumeration(VALUE self)
{
  xmlAttributePtr node;
  xmlEnumerationPtr enm;
  VALUE list;

  Noko_Node_Get_Struct(self, xmlAttribute, node);

  list = rb_ary_new();
  enm = node->tree;

  while (enm) {
    rb_ary_push(list, NOKOGIRI_STR_NEW2(enm->name));
    enm = enm->next;
  }

  return list;
}
```
  An enumeration of possible values

      inspect() Show source   
 
```
# File lib/nokogiri/xml/attribute_decl.rb, line 15
def inspect
  "#<#{self.class.name}:#{format("0x%x", object_id)} #{to_s.inspect}>"
end
```
     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/AttributeDecl.html>

class Nokogiri::XML::Element
=============================



Parent:
cNokogiriXmlNode
 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Element.html>

class Nokogiri::XML::Builder
=============================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
Included modules:
[Nokogiri::ClassResolver](../classresolver)
  [`Nokogiri`](../../nokogiri) builder can be used for building [`XML`](../xml) and [`HTML`](../html4) documents.

 Synopsis:
---------

 
```
builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.products {
      xml.widget {
        xml.id_ "10"
        xml.name "Awesome widget"
      }
    }
  }
end
puts builder.to_xml

```
 Will output:

 
```
<?xml version="1.0"?>
<root>
  <products>
    <widget>
      <id>10</id>
      <name>Awesome widget</name>
    </widget>
  </products>
</root>
```
 ###  [`Builder`](builder) scope

 The builder allows two forms. When the builder is supplied with a block that has a parameter, the outside scope is maintained. This means you can access variables that are outside your builder. If you don’t need outside scope, you can use the builder without the “xml” prefix like this:

 
```
builder = Nokogiri::XML::Builder.new do
  root {
    products {
      widget {
        id_ "10"
        name "Awesome widget"
      }
    }
  }
end

```
 Special Tags
------------

 The builder works by taking advantage of method\_missing. Unfortunately some methods are defined in ruby that are difficult or dangerous to remove. You may want to create tags with the name “type”, “class”, and “id” for example. In that case, you can use an underscore to disambiguate your tag name from the method call.

 Here is an example of using the underscore to disambiguate tag names from ruby methods:

 
```
@objects = [Object.new, Object.new, Object.new]

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.objects {
      @objects.each do |o|
        xml.object {
          xml.type_   o.type
          xml.class_  o.class.name
          xml.id_     o.id
        }
      end
    }
  }
end
puts builder.to_xml

```
 The underscore may be used with any tag name, and the last underscore will just be removed. This code will output the following XML:

 
```
<?xml version="1.0"?>
<root>
  <objects>
    <object>
      <type>Object</type>
      <class>Object</class>
      <id>48390</id>
    </object>
    <object>
      <type>Object</type>
      <class>Object</class>
      <id>48380</id>
    </object>
    <object>
      <type>Object</type>
      <class>Object</class>
      <id>48370</id>
    </object>
  </objects>
</root>
```
 Tag Attributes
--------------

 Tag attributes may be supplied as method arguments. Here is our previous example, but using attributes rather than tags:

 
```
@objects = [Object.new, Object.new, Object.new]

builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.objects {
      @objects.each do |o|
        xml.object(:type => o.type, :class => o.class, :id => o.id)
      end
    }
  }
end
puts builder.to_xml

```
 ### Tag Attribute Short Cuts

 A couple attribute short cuts are available when building tags. The short cuts are available by special method calls when building a tag.

 This example builds an “object” tag with the class attribute “classy” and the id of “thing”:

 
```
builder = Nokogiri::XML::Builder.new do |xml|
  xml.root {
    xml.objects {
      xml.object.classy.thing!
    }
  }
end
puts builder.to_xml

```
 Which will output:

 
```
<?xml version="1.0"?>
<root>
  <objects>
    <object class="classy" id="thing"/>
  </objects>
</root>
```
 All other options are still supported with this syntax, including blocks and extra tag attributes.

 Namespaces
----------

 Namespaces are added similarly to attributes. [`Nokogiri::XML::Builder`](builder) assumes that when an attribute starts with “xmlns”, it is meant to be a namespace:

 
```
builder = Nokogiri::XML::Builder.new { |xml|
  xml.root('xmlns' => 'default', 'xmlns:foo' => 'bar') do
    xml.tenderlove
  end
}
puts builder.to_xml

```
 Will output [`XML`](../xml) like this:

 
```
<?xml version="1.0"?>
<root xmlns:foo="bar" xmlns="default">
  <tenderlove/>
</root>
```
 ### Referencing declared namespaces

 Tags that reference non-default namespaces (i.e. a tag “foo:bar”) can be built by using the [`Nokogiri::XML::Builder#[]`](builder#method-i-5B-5D) method.

 For example:

 
```
builder = Nokogiri::XML::Builder.new do |xml|
  xml.root('xmlns:foo' => 'bar') {
    xml.objects {
      xml['foo'].object.classy.thing!
    }
  }
end
puts builder.to_xml

```
 Will output this XML:

 
```
<?xml version="1.0"?>
<root xmlns:foo="bar">
  <objects>
    <foo:object class="classy" id="thing"/>
  </objects>
</root>
```
 Note the “foo:object” tag.

 ###  [`Namespace`](namespace) inheritance

 In the [`Builder`](builder) context, children will inherit their parent’s namespace. This is the same behavior as if the underlying {XML::Document} set `namespace_inheritance` to `true`:

 
```
result = Nokogiri::XML::Builder.new do |xml|
  xml["soapenv"].Envelope("xmlns:soapenv" => "http://schemas.xmlsoap.org/soap/envelope/") do
    xml.Header
  end
end
result.doc.to_xml
# => <?xml version="1.0" encoding="utf-8"?>
#    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
#      <soapenv:Header/>
#    </soapenv:Envelope>

```
 Users may turn this behavior off by passing a keyword argument `namespace_inheritance:false` to the initializer:

 
```
result = Nokogiri::XML::Builder.new(namespace_inheritance: false) do |xml|
  xml["soapenv"].Envelope("xmlns:soapenv" => "http://schemas.xmlsoap.org/soap/envelope/") do
    xml.Header
    xml["soapenv"].Body # users may explicitly opt into the namespace
  end
end
result.doc.to_xml
# => <?xml version="1.0" encoding="utf-8"?>
#    <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
#      <Header/>
#      <soapenv:Body/>
#    </soapenv:Envelope>

```
 For more information on namespace inheritance, please see {XML::Document#namespace\_inheritance}

  [`Document`](document) Types
-----------------------------

 To create a document type ([`DTD`](dtd)), use the [`Builder#doc`](builder#attribute-i-doc) method to get the current context document. Then call [`Node#create_internal_subset`](node#method-i-create_internal_subset) to create the [`DTD`](dtd) node.

 For example, this Ruby:

 
```
builder = Nokogiri::XML::Builder.new do |xml|
  xml.doc.create_internal_subset(
    'html',
    "-//W3C//DTD HTML 4.01 Transitional//EN",
    "http://www.w3.org/TR/html4/loose.dtd"
  )
  xml.root do
    xml.foo
  end
end

puts builder.to_xml

```
 Will output this xml:

 
```
<?xml version="1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<root>
  <foo/>
</root>
```
     ### Constants

   DEFAULT\_DOCUMENT\_OPTIONS  VALID\_NAMESPACES    Included from [Nokogiri::ClassResolver](../classresolver)  [`related_class`](builder#method-i-related_class) restricts matching namespaces to those matching this set.

      ### Attributes

    context[RW]   A context object for use when the block has no arguments

     doc[RW]   The current [`Document`](document) object being built

     parent[RW]   The parent of the current node being built

      ### Public Class Methods

     new(options = {}, root = nil) { |self| ... } Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 307
def initialize(options = {}, root = nil, &block)
  if root
    @doc = root.document
    @parent = root
  else
    @parent = @doc = related_class("Document").new
  end

  @context = nil
  @arity = nil
  @ns = nil

  options = DEFAULT_DOCUMENT_OPTIONS.merge(options)
  options.each do |k, v|
    @doc.send(:"#{k}=", v)
  end

  return unless block

  @arity = block.arity
  if @arity <= 0
    @context = eval("self", block.binding)
    instance_eval(&block)
  else
    yield self
  end

  @parent = @doc
end
```
  Create a new [`Builder`](builder) object. `options` are sent to the top level [`Document`](document) that is being built.

 Building a document with a particular encoding for example:

 
```
Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|
  ...
end
```
      with(root, &block) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 294
def self.with(root, &block)
  new({}, root, &block)
end
```
  Create a builder with an existing root object. This is for use when you have an existing document that you would like to augment with builder methods. The builder context created will start with the given `root` node.

 For example:

 
```
doc = Nokogiri::XML(File.read('somedoc.xml'))
Nokogiri::XML::Builder.with(doc.at_css('some_tag')) do |xml|
  # ... Use normal builder methods here ...
  xml.awesome # add the "awesome" tag below "some_tag"
end

```
      ### Public Instance Methods

     <<(string) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 390
def <<(string)
  @doc.fragment(string).children.each { |x| insert(x) }
end
```
  Append the given raw [`XML`](../xml) `string` to the document

      [](ns) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 358
def [](ns)
  if @parent != @doc
    @ns = @parent.namespace_definitions.find { |x| x.prefix == ns.to_s }
  end
  return self if @ns

  @parent.ancestors.each do |a|
    next if a == doc

    @ns = a.namespace_definitions.find { |x| x.prefix == ns.to_s }
    return self if @ns
  end

  @ns = { pending: ns.to_s }
  self
end
```
  Build a tag that is associated with namespace `ns`. Raises an ArgumentError if `ns` has not been defined higher in the tree.

      cdata(string) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 345
def cdata(string)
  insert(doc.create_cdata(string))
end
```
  Create a [`CDATA`](cdata) [`Node`](node) with content of `string`

      comment(string) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 351
def comment(string)
  insert(doc.create_comment(string))
end
```
  Create a [`Comment`](comment) [`Node`](node) with content of `string`

       related\_class(class\_name) → Class  Show source   
 
```
# File lib/nokogiri/class_resolver.rb, line 46
def related_class(class_name)
  klass = nil
  inspecting = self.class

  while inspecting
    namespace_path = inspecting.name.split("::")[0..-2]
    inspecting = inspecting.superclass

    next unless VALID_NAMESPACES.include?(namespace_path.last)

    related_class_name = (namespace_path << class_name).join("::")
    klass = begin
      Object.const_get(related_class_name)
    rescue NameError
      nil
    end
    break if klass
  end
  klass
end
```
   Included from [Nokogiri::ClassResolver](../classresolver)  Find a class constant within the

 Some examples:

 
```
Nokogiri::XML::Document.new.related_class("DocumentFragment")
# => Nokogiri::XML::DocumentFragment
Nokogiri::HTML4::Document.new.related_class("DocumentFragment")
# => Nokogiri::HTML4::DocumentFragment

```
 Note this will also work for subclasses that follow the same convention, e.g.:

 
```
Loofah::HTML::Document.new.related_class("DocumentFragment")
# => Loofah::HTML::DocumentFragment

```
 And even if it’s a subclass, this will iterate through the superclasses:

 
```
class ThisIsATopLevelClass < Nokogiri::HTML4::Builder ; end
ThisIsATopLevelClass.new.related_class("Document")
# => Nokogiri::HTML4::Document

```
      text(string) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 339
def text(string)
  insert(@doc.create_text_node(string))
end
```
  Create a [`Text`](text) [`Node`](node) with content of `string`

      to\_xml(\*args) Show source   
 
```
# File lib/nokogiri/xml/builder.rb, line 377
def to_xml(*args)
  if Nokogiri.jruby?
    options = args.first.is_a?(Hash) ? args.shift : {}
    unless options[:save_with]
      options[:save_with] = Node::SaveOptions::AS_BUILDER
    end
    args.insert(0, options)
  end
  @doc.to_xml(*args)
end
```
  Convert this [`Builder`](builder) object to [`XML`](../xml)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Builder.html>

class Nokogiri::XML::CDATA
===========================



Parent:
cNokogiriXmlText
  CData represents a CData node in an xml document.

     ### Public Class Methods

      new(document, content)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  xmlNodePtr node;
  VALUE doc;
  VALUE content;
  VALUE rest;
  VALUE rb_node;
  xmlChar *content_str = NULL;
  int content_str_len = 0;

  rb_scan_args(argc, argv, "2*", &doc, &content, &rest);

  Noko_Node_Get_Struct(doc, xmlDoc, xml_doc);

  if (!NIL_P(content)) {
    content_str = (xmlChar *)StringValuePtr(content);
    content_str_len = RSTRING_LENINT(content);
  }

  node = xmlNewCDataBlock(xml_doc->doc, content_str, content_str_len);

  noko_xml_document_pin_node(node);

  rb_node = noko_xml_node_wrap(klass, node);
  rb_obj_call_init(rb_node, argc, argv);

  if (rb_block_given_p()) { rb_yield(rb_node); }

  return rb_node;
}
```
  Create a new [`CDATA`](cdata) element on the `document` with `content`

 If `content` cannot be implicitly converted to a string, this method will raise a TypeError exception.

      ### Public Instance Methods

     name() Show source   
 
```
# File lib/nokogiri/xml/cdata.rb, line 8
def name
  "#cdata-section"
end
```
  Get the name of this [`CDATA`](cdata) node

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/CDATA.html>

class Nokogiri::XML::DTD
=========================



Parent:
cNokogiriXmlNode
  [`Nokogiri::XML::DTD`](dtd) wraps [`DTD`](dtd) nodes in an [`XML`](../xml) document

     ### Public Instance Methods

      attributes  Show source   
 
```
static VALUE
attributes(VALUE self)
{
  xmlDtdPtr dtd;
  VALUE hash;

  Noko_Node_Get_Struct(self, xmlDtd, dtd);

  hash = rb_hash_new();

  if (!dtd->attributes) { return hash; }

  xmlHashScan((xmlHashTablePtr)dtd->attributes, element_copier, (void *)hash);

  return hash;
}
```
  Get a hash of the attributes for this [`DTD`](dtd).

      each() { |key, value| ... } Show source   
 
```
# File lib/nokogiri/xml/dtd.rb, line 17
def each
  attributes.each do |key, value|
    yield([key, value])
  end
end
```
        elements  Show source   
 
```
static VALUE
elements(VALUE self)
{
  xmlDtdPtr dtd;
  VALUE hash;

  Noko_Node_Get_Struct(self, xmlDtd, dtd);

  if (!dtd->elements) { return Qnil; }

  hash = rb_hash_new();

  xmlHashScan((xmlHashTablePtr)dtd->elements, element_copier, (void *)hash);

  return hash;
}
```
  Get a hash of the elements for this [`DTD`](dtd).

       entities  Show source   
 
```
static VALUE
entities(VALUE self)
{
  xmlDtdPtr dtd;
  VALUE hash;

  Noko_Node_Get_Struct(self, xmlDtd, dtd);

  if (!dtd->entities) { return Qnil; }

  hash = rb_hash_new();

  xmlHashScan((xmlHashTablePtr)dtd->entities, element_copier, (void *)hash);

  return hash;
}
```
  Get a hash of the elements for this [`DTD`](dtd).

       external\_id  Show source   
 
```
static VALUE
external_id(VALUE self)
{
  xmlDtdPtr dtd;
  Noko_Node_Get_Struct(self, xmlDtd, dtd);

  if (!dtd->ExternalID) { return Qnil; }

  return NOKOGIRI_STR_NEW2(dtd->ExternalID);
}
```
  Get the External ID for this [`DTD`](dtd)

      html5\_dtd?() Show source   
 
```
# File lib/nokogiri/xml/dtd.rb, line 27
def html5_dtd?
  html_dtd? &&
    external_id.nil? &&
    (system_id.nil? || system_id == "about:legacy-compat")
end
```
       html\_dtd?() Show source   
 
```
# File lib/nokogiri/xml/dtd.rb, line 23
def html_dtd?
  name.casecmp("html").zero?
end
```
       keys() Show source   
 
```
# File lib/nokogiri/xml/dtd.rb, line 13
def keys
  attributes.keys
end
```
        notations() → Hash<name(String)⇒Notation>  Show source   
 
```
static VALUE
notations(VALUE self)
{
  xmlDtdPtr dtd;
  VALUE hash;

  Noko_Node_Get_Struct(self, xmlDtd, dtd);

  if (!dtd->notations) { return Qnil; }

  hash = rb_hash_new();

  xmlHashScan((xmlHashTablePtr)dtd->notations, notation_copier, (void *)hash);

  return hash;
}
```
   Returns   All the notations for this [`DTD`](dtd) in a Hash of [`Notation`](notation) `name` to [`Notation`](notation).

         system\_id  Show source   
 
```
static VALUE
system_id(VALUE self)
{
  xmlDtdPtr dtd;
  Noko_Node_Get_Struct(self, xmlDtd, dtd);

  if (!dtd->SystemID) { return Qnil; }

  return NOKOGIRI_STR_NEW2(dtd->SystemID);
}
```
  Get the System ID for this [`DTD`](dtd)

       validate(document)  Show source   
 
```
static VALUE
validate(VALUE self, VALUE document)
{
  xmlDocPtr doc;
  xmlDtdPtr dtd;
  xmlValidCtxtPtr ctxt;
  VALUE error_list;

  Noko_Node_Get_Struct(self, xmlDtd, dtd);
  Noko_Node_Get_Struct(document, xmlDoc, doc);
  error_list = rb_ary_new();

  ctxt = xmlNewValidCtxt();

  xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);

  xmlValidateDtd(ctxt, doc, dtd);

  xmlSetStructuredErrorFunc(NULL, NULL);

  xmlFreeValidCtxt(ctxt);

  return error_list;
}
```
  Validate `document` returning a list of errors

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/DTD.html>

class Nokogiri::XML::Document
==============================



Parent:
cNokogiriXmlNode
  [`Nokogiri::XML::Document`](document) wraps an xml document.

 [`Nokogiri::XML::Document`](document) is the main entry point for dealing with [`XML`](../xml) documents. The [`Document`](document) is created by parsing an [`XML`](../xml) document. See [`Nokogiri::XML::Document.parse`](document#method-c-parse) for more information on parsing.

 For searching a [`Document`](document), see [`Nokogiri::XML::Searchable#css`](searchable#method-i-css) and [`Nokogiri::XML::Searchable#xpath`](searchable#method-i-xpath)

     ### Constants

   NCNAME\_CHAR  NCNAME\_RE  NCNAME\_START\_CHAR   See [www.w3.org/TR/REC-xml-names/#ns-decl](http://www.w3.org/TR/REC-xml-names/#ns-decl) for more details. Note that we’re not attempting to handle unicode characters partly because libxml2 doesn’t handle unicode characters in NCNAMEs.

      ### Attributes

    errors[RW]   The errors found while parsing a document.

  Returns   Array<Nokogiri::XML::SyntaxError>

       namespace\_inheritance[RW]   When ‘true`, reparented elements without a namespace will inherit their new parent’s namespace (if one exists). Defaults to ‘false`.

  Returns   Boolean

   **Example:** Default behavior of namespace inheritance

 
```
xml = <<~EOF
        <root xmlns:foo="http://nokogiri.org/default_ns/test/foo">
          <foo:parent>
          </foo:parent>
        </root>
      EOF
doc = Nokogiri::XML(xml)
parent = doc.at_xpath("//foo:parent", "foo" => "http://nokogiri.org/default_ns/test/foo")
parent.add_child("<child></child>")
doc.to_xml
# => <?xml version="1.0"?>
#    <root xmlns:foo="http://nokogiri.org/default_ns/test/foo">
#      <foo:parent>
#        <child/>
#      </foo:parent>
#    </root>

```
 **Example:** Setting namespace inheritance to ‘true`

 
```
xml = <<~EOF
        <root xmlns:foo="http://nokogiri.org/default_ns/test/foo">
          <foo:parent>
          </foo:parent>
        </root>
      EOF
doc = Nokogiri::XML(xml)
doc.namespace_inheritance = true
parent = doc.at_xpath("//foo:parent", "foo" => "http://nokogiri.org/default_ns/test/foo")
parent.add_child("<child></child>")
doc.to_xml
# => <?xml version="1.0"?>
#    <root xmlns:foo="http://nokogiri.org/default_ns/test/foo">
#      <foo:parent>
#        <foo:child/>
#      </foo:parent>
#    </root>

```
 Since v1.12.4

      ### Public Class Methods

      new(version = default)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr doc;
  VALUE version, rest, rb_doc ;

  rb_scan_args(argc, argv, "0*", &rest);
  version = rb_ary_entry(rest, (long)0);
  if (NIL_P(version)) { version = rb_str_new2("1.0"); }

  doc = xmlNewDoc((xmlChar *)StringValueCStr(version));
  rb_doc = noko_xml_document_wrap_with_init_args(klass, doc, argc, argv);
  return rb_doc ;
}
```
  Create a new document with `version` (defaults to “1.0”)

      parse(string\_or\_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT\_XML) { |options| ... } Show source   
 
```
# File lib/nokogiri/xml/document.rb, line 48
def parse(string_or_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML)
  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil

  if empty_doc?(string_or_io)
    if options.strict?
      raise Nokogiri::XML::SyntaxError, "Empty document"
    else
      return encoding ? new.tap { |i| i.encoding = encoding } : new
    end
  end

  doc = if string_or_io.respond_to?(:read)
    if string_or_io.is_a?(Pathname)
      # resolve the Pathname to the file and open it as an IO object, see #2110
      string_or_io = string_or_io.expand_path.open
      url ||= string_or_io.path
    end

    read_io(string_or_io, url, encoding, options.to_i)
  else
    # read_memory pukes on empty docs
    read_memory(string_or_io, url, encoding, options.to_i)
  end

  # do xinclude processing
  doc.do_xinclude(options) if options.xinclude?

  doc
end
```
  Parse an [`XML`](../xml) file.

 `string_or_io` may be a String, or any object that responds to *read* and *close* such as an IO, or StringIO.

 `url` (optional) is the URI where this document is located.

 `encoding` (optional) is the encoding that should be used when processing the document.

 `options` (optional) is a configuration object that sets options during parsing, such as Nokogiri::XML::ParseOptions::RECOVER. See the [`Nokogiri::XML::ParseOptions`](parseoptions) for more information.

 `block` (optional) is passed a configuration object on which parse options may be set.

 By default, [`Nokogiri`](../../nokogiri) treats documents as untrusted, and so does not attempt to load DTDs or access the network. See [`Nokogiri::XML::ParseOptions`](parseoptions) for a complete list of options; and that module’s DEFAULT\_XML constant for what’s set (and not set) by default.

 [`Nokogiri.XML()`](../../nokogiri#method-c-XML) is a convenience method which will call this method.

       read\_io(io, url, encoding, options)  Show source   
 
```
static VALUE
read_io(VALUE klass,
        VALUE io,
        VALUE url,
        VALUE encoding,
        VALUE options)
{
  const char *c_url    = NIL_P(url)      ? NULL : StringValueCStr(url);
  const char *c_enc    = NIL_P(encoding) ? NULL : StringValueCStr(encoding);
  VALUE error_list      = rb_ary_new();
  VALUE document;
  xmlDocPtr doc;

  xmlResetLastError();
  xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);

  doc = xmlReadIO(
          (xmlInputReadCallback)noko_io_read,
          (xmlInputCloseCallback)noko_io_close,
          (void *)io,
          c_url,
          c_enc,
          (int)NUM2INT(options)
        );
  xmlSetStructuredErrorFunc(NULL, NULL);

  if (doc == NULL) {
    xmlErrorPtr error;

    xmlFreeDoc(doc);

    error = xmlGetLastError();
    if (error) {
      rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error));
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  document = noko_xml_document_wrap(klass, doc);
  rb_iv_set(document, "@errors", error_list);
  return document;
}
```
  Create a new document from an IO object

       read\_memory(string, url, encoding, options)  Show source   
 
```
static VALUE
read_memory(VALUE klass,
            VALUE string,
            VALUE url,
            VALUE encoding,
            VALUE options)
{
  const char *c_buffer = StringValuePtr(string);
  const char *c_url    = NIL_P(url)      ? NULL : StringValueCStr(url);
  const char *c_enc    = NIL_P(encoding) ? NULL : StringValueCStr(encoding);
  int len               = (int)RSTRING_LEN(string);
  VALUE error_list      = rb_ary_new();
  VALUE document;
  xmlDocPtr doc;

  xmlResetLastError();
  xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);
  doc = xmlReadMemory(c_buffer, len, c_url, c_enc, (int)NUM2INT(options));
  xmlSetStructuredErrorFunc(NULL, NULL);

  if (doc == NULL) {
    xmlErrorPtr error;

    xmlFreeDoc(doc);

    error = xmlGetLastError();
    if (error) {
      rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error));
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  document = noko_xml_document_wrap(klass, doc);
  rb_iv_set(document, "@errors", error_list);
  return document;
}
```
  Create a new document from a String

       wrap(java\_document) → Nokogiri::XML::Document  Show source   
 
```
# File lib/nokogiri/xml/document.rb, line 91
      
```
  ⚠ This method is only available when running JRuby.

 Create a [`Document`](document) using an existing Java DOM document object.

 The returned [`Document`](document) shares the same underlying data structure as the Java object, so changes in one are reflected in the other.

  Parameters   * ‘java\_document` (Java::OrgW3cDom::Document) (The class `Java::OrgW3cDom::Document` is also accessible as `org.w3c.dom.Document`.)

  Returns   [`Nokogiri::XML::Document`](document)

   See also #to\_java

      ### Public Instance Methods

      canonicalize(mode=XML\_C14N\_1\_0,inclusive\_namespaces=nil,with\_comments=false)  Show source    canonicalize { |obj, parent| ... }    
 
```
static VALUE
rb_xml_document_canonicalize(int argc, VALUE *argv, VALUE self)
{
  VALUE rb_mode;
  VALUE rb_namespaces;
  VALUE rb_comments_p;
  int c_mode = 0;
  xmlChar **c_namespaces;

  xmlDocPtr c_doc;
  xmlOutputBufferPtr c_obuf;
  xmlC14NIsVisibleCallback c_callback_wrapper = NULL;
  void *rb_callback = NULL;

  VALUE rb_cStringIO;
  VALUE rb_io;

  rb_scan_args(argc, argv, "03", &rb_mode, &rb_namespaces, &rb_comments_p);
  if (!NIL_P(rb_mode)) {
    Check_Type(rb_mode, T_FIXNUM);
    c_mode = NUM2INT(rb_mode);
  }
  if (!NIL_P(rb_namespaces)) {
    Check_Type(rb_namespaces, T_ARRAY);
    if (c_mode == XML_C14N_1_0 || c_mode == XML_C14N_1_1) {
      rb_raise(rb_eRuntimeError, "This canonicalizer does not support this operation");
    }
  }

  Data_Get_Struct(self, xmlDoc, c_doc);

  rb_cStringIO = rb_const_get_at(rb_cObject, rb_intern("StringIO"));
  rb_io = rb_class_new_instance(0, 0, rb_cStringIO);
  c_obuf = xmlAllocOutputBuffer(NULL);

  c_obuf->writecallback = (xmlOutputWriteCallback)noko_io_write;
  c_obuf->closecallback = (xmlOutputCloseCallback)noko_io_close;
  c_obuf->context = (void *)rb_io;

  if (rb_block_given_p()) {
    c_callback_wrapper = block_caller;
    rb_callback = (void *)rb_block_proc();
  }

  if (NIL_P(rb_namespaces)) {
    c_namespaces = NULL;
  } else {
    long ns_len = RARRAY_LEN(rb_namespaces);
    c_namespaces = ruby_xcalloc((size_t)ns_len + 1, sizeof(xmlChar *));
    for (int j = 0 ; j < ns_len ; j++) {
      VALUE entry = rb_ary_entry(rb_namespaces, j);
      c_namespaces[j] = (xmlChar *)StringValueCStr(entry);
    }
  }

  xmlC14NExecute(c_doc, c_callback_wrapper, rb_callback,
                 c_mode,
                 c_namespaces,
                 (int)RTEST(rb_comments_p),
                 c_obuf);

  ruby_xfree(c_namespaces);
  xmlOutputBufferClose(c_obuf);

  return rb_funcall(rb_io, rb_intern("string"), 0);
}
```
  Canonicalize a document and return the results. Takes an optional block that takes two parameters: the `obj` and that node’s `parent`. The `obj` will be either a [`Nokogiri::XML::Node`](node), or a [`Nokogiri::XML::Namespace`](namespace) The block must return a non-nil, non-false value if the `obj` passed in should be included in the canonicalized document.

       create\_entity(name, type, external\_id, system\_id, content)  Show source   
 
```
static VALUE
create_entity(int argc, VALUE *argv, VALUE self)
{
  VALUE name;
  VALUE type;
  VALUE external_id;
  VALUE system_id;
  VALUE content;
  xmlEntityPtr ptr;
  xmlDocPtr doc ;

  Data_Get_Struct(self, xmlDoc, doc);

  rb_scan_args(argc, argv, "14", &name, &type, &external_id, &system_id,
               &content);

  xmlResetLastError();
  ptr = xmlAddDocEntity(
          doc,
          (xmlChar *)(NIL_P(name)        ? NULL                        : StringValueCStr(name)),
          (int)(NIL_P(type)        ? XML_INTERNAL_GENERAL_ENTITY : NUM2INT(type)),
          (xmlChar *)(NIL_P(external_id) ? NULL                        : StringValueCStr(external_id)),
          (xmlChar *)(NIL_P(system_id)   ? NULL                        : StringValueCStr(system_id)),
          (xmlChar *)(NIL_P(content)     ? NULL                        : StringValueCStr(content))
        );

  if (NULL == ptr) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error));
    } else {
      rb_raise(rb_eRuntimeError, "Could not create entity");
    }

    return Qnil;
  }

  return noko_xml_node_wrap(cNokogiriXmlEntityDecl, (xmlNodePtr)ptr);
}
```
  Create a new entity named `name`.

 `type` is an integer representing the type of entity to be created, and it defaults to Nokogiri::XML::EntityDecl::INTERNAL\_GENERAL. See the constants on [`Nokogiri::XML::EntityDecl`](entitydecl) for more information.

 `external_id`, `system_id`, and `content` set the External ID, System ID, and content respectively. All of these parameters are optional.

       dup  Show source   
 
```
static VALUE
duplicate_document(int argc, VALUE *argv, VALUE self)
{
  xmlDocPtr doc, dup;
  VALUE copy;
  VALUE level;

  if (rb_scan_args(argc, argv, "01", &level) == 0) {
    level = INT2NUM((long)1);
  }

  Data_Get_Struct(self, xmlDoc, doc);

  dup = xmlCopyDoc(doc, (int)NUM2INT(level));

  if (dup == NULL) { return Qnil; }

  dup->type = doc->type;
  copy = noko_xml_document_wrap(rb_obj_class(self), dup);
  rb_iv_set(copy, "@errors", rb_iv_get(self, "@errors"));
  return copy ;
}
```
  Copy this [`Document`](document). An optional depth may be passed in, but it defaults to a deep copy. 0 is a shallow copy, 1 is a deep copy.

       encoding  Show source   
 
```
static VALUE
encoding(VALUE self)
{
  xmlDocPtr doc;
  Data_Get_Struct(self, xmlDoc, doc);

  if (!doc->encoding) { return Qnil; }
  return NOKOGIRI_STR_NEW2(doc->encoding);
}
```
  Get the encoding for this [`Document`](document)

       encoding= encoding  Show source   
 
```
static VALUE
set_encoding(VALUE self, VALUE encoding)
{
  xmlDocPtr doc;
  Data_Get_Struct(self, xmlDoc, doc);

  if (doc->encoding) {
    xmlFree(DISCARD_CONST_QUAL_XMLCHAR(doc->encoding));
  }

  doc->encoding = xmlStrdup((xmlChar *)StringValueCStr(encoding));

  return encoding;
}
```
  Set the encoding string for this [`Document`](document)

       remove\_namespaces!  Show source   
 
```
static VALUE
remove_namespaces_bang(VALUE self)
{
  xmlDocPtr doc ;
  Data_Get_Struct(self, xmlDoc, doc);

  recursively_remove_namespaces_from_node((xmlNodePtr)doc);
  return self;
}
```
  Remove all namespaces from all nodes in the document.

 This could be useful for developers who either don’t understand namespaces or don’t care about them.

 The following example shows a use case, and you can decide for yourself whether this is a good thing or not:

 
```
doc = Nokogiri::XML <<-EOXML
   <root>
     <car xmlns:part="http://general-motors.com/">
       <part:tire>Michelin Model XGV</part:tire>
     </car>
     <bicycle xmlns:part="http://schwinn.com/">
       <part:tire>I'm a bicycle tire!</part:tire>
     </bicycle>
   </root>
   EOXML

doc.xpath("//tire").to_s # => ""
doc.xpath("//part:tire", "part" => "http://general-motors.com/").to_s # => "<part:tire>Michelin Model XGV</part:tire>"
doc.xpath("//part:tire", "part" => "http://schwinn.com/").to_s # => "<part:tire>I'm a bicycle tire!</part:tire>"

doc.remove_namespaces!

doc.xpath("//tire").to_s # => "<tire>Michelin Model XGV</tire><tire>I'm a bicycle tire!</tire>"
doc.xpath("//part:tire", "part" => "http://general-motors.com/").to_s # => ""
doc.xpath("//part:tire", "part" => "http://schwinn.com/").to_s # => ""

```
 For more information on why this probably is **not** a good thing in general, please direct your browser to [tenderlovemaking.com/2009/04/23/namespaces-in-xml.html](http://tenderlovemaking.com/2009/04/23/namespaces-in-xml.html)

       root  Show source   
 
```
static VALUE
rb_xml_document_root(VALUE self)
{
  xmlDocPtr c_document;
  xmlNodePtr c_root;

  Data_Get_Struct(self, xmlDoc, c_document);

  c_root = xmlDocGetRootElement(c_document);
  if (!c_root) {
    return Qnil;
  }

  return noko_xml_node_wrap(Qnil, c_root) ;
}
```
  Get the root node for this document.

       root=  Show source   
 
```
static VALUE
rb_xml_document_root_set(VALUE self, VALUE rb_new_root)
{
  xmlDocPtr c_document;
  xmlNodePtr c_new_root = NULL, c_current_root;

  Data_Get_Struct(self, xmlDoc, c_document);

  c_current_root = xmlDocGetRootElement(c_document);
  if (c_current_root) {
    xmlUnlinkNode(c_current_root);
    noko_xml_document_pin_node(c_current_root);
  }

  if (!NIL_P(rb_new_root)) {
    if (!rb_obj_is_kind_of(rb_new_root, cNokogiriXmlNode)) {
      rb_raise(rb_eArgError,
               "expected Nokogiri::XML::Node but received %"PRIsVALUE,
               rb_obj_class(rb_new_root));
    }

    Noko_Node_Get_Struct(rb_new_root, xmlNode, c_new_root);

    /* If the new root's document is not the same as the current document,
     * then we need to dup the node in to this document. */
    if (c_new_root->doc != c_document) {
      c_new_root = xmlDocCopyNode(c_new_root, c_document, 1);
      if (!c_new_root) {
        rb_raise(rb_eRuntimeError, "Could not reparent node (xmlDocCopyNode)");
      }
    }
  }

  xmlDocSetRootElement(c_document, c_new_root);

  return rb_new_root;
}
```
  Set the root element on this document

       to\_java() → Java::OrgW3cDom::Document  Show source   
 
```
# File lib/nokogiri/xml/document.rb, line 109
      
```
  ⚠ This method is only available when running JRuby.

 Returns the underlying Java DOM document object for this document.

 The returned Java object shares the same underlying data structure as this document, so changes in one are reflected in the other.

  Returns   Java::OrgW3cDom::Document (The class ‘Java::OrgW3cDom::Document` is also accessible as `org.w3c.dom.Document`.)

   See also [`Document.wrap`](document#method-c-wrap)

       url  Show source   
 
```
static VALUE
url(VALUE self)
{
  xmlDocPtr doc;
  Data_Get_Struct(self, xmlDoc, doc);

  if (doc->URL) { return NOKOGIRI_STR_NEW2(doc->URL); }

  return Qnil;
}
```
  Get the url name for this document.

       version  Show source   
 
```
static VALUE
version(VALUE self)
{
  xmlDocPtr doc;
  Data_Get_Struct(self, xmlDoc, doc);

  if (!doc->version) { return Qnil; }
  return NOKOGIRI_STR_NEW2(doc->version);
}
```
  Get the [`XML`](../xml) version for this [`Document`](document)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Document.html>

class Nokogiri::XML::DocumentFragment
======================================



Parent:
cNokogiriXmlNode
  [`DocumentFragment`](documentfragment) represents a [`DocumentFragment`](documentfragment) node in an xml document.

     ### Public Class Methods

      new(document)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  xmlNodePtr node;
  VALUE document;
  VALUE rest;
  VALUE rb_node;

  rb_scan_args(argc, argv, "1*", &document, &rest);

  Data_Get_Struct(document, xmlDoc, xml_doc);

  node = xmlNewDocFragment(xml_doc->doc);

  noko_xml_document_pin_node(node);

  rb_node = noko_xml_node_wrap(klass, node);
  rb_obj_call_init(rb_node, argc, argv);

  return rb_node;
}
```
  Create a new [`DocumentFragment`](documentfragment) element on the `document`

      new(document, tags = nil, ctx = nil, options = ParseOptions::DEFAULT\_XML) { |options| ... } Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 19
def initialize(document, tags = nil, ctx = nil, options = ParseOptions::DEFAULT_XML)
  return self unless tags

  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  children = if ctx
    # Fix for issue#490
    if Nokogiri.jruby?
      # fix for issue #770
      ctx.parse("<root #{namespace_declarations(ctx)}>#{tags}</root>", options).children
    else
      ctx.parse(tags, options)
    end
  else
    wrapper_doc = XML::Document.parse("<root>#{tags}</root>", nil, nil, options)
    self.errors = wrapper_doc.errors
    wrapper_doc.xpath("/root/node()")
  end
  children.each { |child| child.parent = self }
end
```
  Create a new [`DocumentFragment`](documentfragment) from `tags`.

 If `ctx` is present, it is used as a context node for the subtree created, e.g., namespaces will be resolved relative to `ctx`.

      parse(tags, options = ParseOptions::DEFAULT\_XML, &block) Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 9
def self.parse(tags, options = ParseOptions::DEFAULT_XML, &block)
  new(XML::Document.new, tags, nil, options, &block)
end
```
  Create a [`Nokogiri::XML::DocumentFragment`](documentfragment) from `tags`

      ### Public Instance Methods

      css \*rules, [namespace-bindings, custom-pseudo-class]  Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 102
def css(*args)
  if children.any?
    children.css(*args) # 'children' is a smell here
  else
    NodeSet.new(document)
  end
end
```
  Search this fragment for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example:

 For more information see [`Nokogiri::XML::Searchable#css`](searchable#method-i-css)

       deconstruct() → Array  Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 190
def deconstruct
  children.to_a
end
```
  Returns the root nodes of this document fragment as an array, to use in pattern matching.

 💡 Note that text nodes are returned as well as elements. If you wish to operate only on root elements, you should deconstruct the array returned by `DocumentFragment#elements`.

 ⚡ This is an experimental feature, available since v1.14.0

 **Example**

 
```
frag = Nokogiri::HTML5.fragment(<<~HTML)
  <div>Start</div>
  This is a <a href="#jump">shortcut</a> for you.
  <div>End</div>
HTML

frag.deconstruct
# => [#(Element:0x35c { name = "div", children = [ #(Text "Start")] }),
#     #(Text "\n" + "This is a "),
#     #(Element:0x370 {
#       name = "a",
#       attributes = [ #(Attr:0x384 { name = "href", value = "#jump" })],
#       children = [ #(Text "shortcut")]
#       }),
#     #(Text " for you.\n"),
#     #(Element:0x398 { name = "div", children = [ #(Text "End")] }),
#     #(Text "\n")]

```
 **Example** only the elements, not the text nodes.

 
```
frag.elements.deconstruct
# => [#(Element:0x35c { name = "div", children = [ #(Text "Start")] }),
#     #(Element:0x370 {
#       name = "a",
#       attributes = [ #(Attr:0x384 { name = "href", value = "#jump" })],
#       children = [ #(Text "shortcut")]
#       }),
#     #(Element:0x398 { name = "div", children = [ #(Text "End")] })]

```
      dup() Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 42
def dup
  new_document = document.dup
  new_fragment = self.class.new(new_document)
  children.each do |child|
    child.dup(1, new_document).parent = new_fragment
  end
  new_fragment
end
```
       errors() Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 136
def errors
  document.errors
end
```
  A list of [`Nokogiri::XML::SyntaxError`](syntaxerror) found when parsing a document

      fragment(data) Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 144
def fragment(data)
  document.fragment(data)
end
```
       name() Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 54
def name
  "#document-fragment"
end
```
  return the name for [`DocumentFragment`](documentfragment)

       search \*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]  Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 121
def search(*rules)
  rules, handler, ns, binds = extract_params(rules)

  rules.inject(NodeSet.new(document)) do |set, rule|
    set + if Searchable::LOOKS_LIKE_XPATH.match?(rule)
      xpath(*[rule, ns, handler, binds].compact)
    else
      children.css(*[rule, ns, handler].compact) # 'children' is a smell here
    end
  end
end
```
  Search this fragment for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries.

 For more information see [`Nokogiri::XML::Searchable#search`](searchable#method-i-search)

      serialize()    Alias for: [to\_s](documentfragment#method-i-to_s)      to\_html(\*args) Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 67
def to_html(*args)
  if Nokogiri.jruby?
    options = args.first.is_a?(Hash) ? args.shift : {}
    options[:save_with] ||= Node::SaveOptions::DEFAULT_HTML
    args.insert(0, options)
  end
  children.to_html(*args)
end
```
  Convert this [`DocumentFragment`](documentfragment) to html See [`Nokogiri::XML::NodeSet#to_html`](nodeset#method-i-to_html)

      to\_s() Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 60
def to_s
  children.to_s
end
```
  Convert this [`DocumentFragment`](documentfragment) to a string

   Also aliased as: [serialize](documentfragment#method-i-serialize)      to\_xhtml(\*args) Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 79
def to_xhtml(*args)
  if Nokogiri.jruby?
    options = args.first.is_a?(Hash) ? args.shift : {}
    options[:save_with] ||= Node::SaveOptions::DEFAULT_XHTML
    args.insert(0, options)
  end
  children.to_xhtml(*args)
end
```
  Convert this [`DocumentFragment`](documentfragment) to xhtml See [`Nokogiri::XML::NodeSet#to_xhtml`](nodeset#method-i-to_xhtml)

      to\_xml(\*args) Show source   
 
```
# File lib/nokogiri/xml/document_fragment.rb, line 91
def to_xml(*args)
  children.to_xml(*args)
end
```
  Convert this [`DocumentFragment`](documentfragment) to xml See [`Nokogiri::XML::NodeSet#to_xml`](nodeset#method-i-to_xml)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/DocumentFragment.html>

class Nokogiri::XML::ElementContent
====================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  Represents the allowed content in an [`Element`](element) Declaration inside a DTD:

 
```
<?xml version="1.0"?><?TEST-STYLE PIDATA?>
<!DOCTYPE staff SYSTEM "staff.dtd" [
   <!ELEMENT div1 (head, (p | list | note)*, div2*)>
]>
</root>
```
 [`ElementContent`](elementcontent) represents the tree inside the <!ELEMENT> tag shown above that lists the possible content for the div1 tag.

     ### Constants

   ELEMENT  MULT  ONCE   Possible content occurrences

  OPT  OR  PCDATA   Possible definitions of type

  PLUS  SEQ      ### Attributes

    document[R]      ### Public Instance Methods

     children() Show source   
 
```
# File lib/nokogiri/xml/element_content.rb, line 33
def children
  [c1, c2].compact
end
```
  Get the children of this [`ElementContent`](elementcontent) node

       name  Show source   
 
```
static VALUE
get_name(VALUE self)
{
  xmlElementContentPtr elem;
  Data_Get_Struct(self, xmlElementContent, elem);

  if (!elem->name) { return Qnil; }
  return NOKOGIRI_STR_NEW2(elem->name);
}
```
  Get the require element `name`

       occur  Show source   
 
```
static VALUE
get_occur(VALUE self)
{
  xmlElementContentPtr elem;
  Data_Get_Struct(self, xmlElementContent, elem);

  return INT2NUM(elem->ocur);
}
```
  Get the element content `occur` flag. Possible values are [`ONCE`](elementcontent#ONCE), [`OPT`](elementcontent#OPT), [`MULT`](elementcontent#MULT) or [`PLUS`](elementcontent#PLUS).

       prefix  Show source   
 
```
static VALUE
get_prefix(VALUE self)
{
  xmlElementContentPtr elem;
  Data_Get_Struct(self, xmlElementContent, elem);

  if (!elem->prefix) { return Qnil; }

  return NOKOGIRI_STR_NEW2(elem->prefix);
}
```
  Get the element content namespace `prefix`.

       type  Show source   
 
```
static VALUE
get_type(VALUE self)
{
  xmlElementContentPtr elem;
  Data_Get_Struct(self, xmlElementContent, elem);

  return INT2NUM(elem->type);
}
```
  Get the element content `type`. Possible values are [`PCDATA`](elementcontent#PCDATA), [`ELEMENT`](elementcontent#ELEMENT), [`SEQ`](elementcontent#SEQ), or [`OR`](elementcontent#OR).

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/ElementContent.html>

class Nokogiri::XML::ElementDecl
=================================



Parent:
cNokogiriXmlNode
    ### Public Instance Methods

      content  Show source   
 
```
static VALUE
content(VALUE self)
{
  xmlElementPtr node;
  Noko_Node_Get_Struct(self, xmlElement, node);

  if (!node->content) { return Qnil; }

  return noko_xml_element_content_wrap(
           rb_funcall(self, id_document, 0),
           node->content
         );
}
```
  The allowed content for this [`ElementDecl`](elementdecl)

       element\_type  Show source   
 
```
static VALUE
element_type(VALUE self)
{
  xmlElementPtr node;
  Noko_Node_Get_Struct(self, xmlElement, node);
  return INT2NUM(node->etype);
}
```
  The [`element_type`](elementdecl#method-i-element_type)

      inspect() Show source   
 
```
# File lib/nokogiri/xml/element_decl.rb, line 10
def inspect
  "#<#{self.class.name}:#{format("0x%x", object_id)} #{to_s.inspect}>"
end
```
        prefix  Show source   
 
```
static VALUE
prefix(VALUE self)
{
  xmlElementPtr node;
  Noko_Node_Get_Struct(self, xmlElement, node);

  if (!node->prefix) { return Qnil; }

  return NOKOGIRI_STR_NEW2(node->prefix);
}
```
  The namespace prefix for this [`ElementDecl`](elementdecl)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/ElementDecl.html>

class Nokogiri::XML::EntityReference
=====================================



Parent:
cNokogiriXmlNode
  [`EntityReference`](entityreference) represents an [`EntityReference`](entityreference) node in an xml document.

     ### Public Class Methods

      new(document, content)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  xmlNodePtr node;
  VALUE document;
  VALUE name;
  VALUE rest;
  VALUE rb_node;

  rb_scan_args(argc, argv, "2*", &document, &name, &rest);

  Data_Get_Struct(document, xmlDoc, xml_doc);

  node = xmlNewReference(
           xml_doc,
           (const xmlChar *)StringValueCStr(name)
         );

  noko_xml_document_pin_node(node);

  rb_node = noko_xml_node_wrap(klass, node);
  rb_obj_call_init(rb_node, argc, argv);

  if (rb_block_given_p()) { rb_yield(rb_node); }

  return rb_node;
}
```
  Create a new [`EntityReference`](entityreference) element on the `document` with `name`

      ### Public Instance Methods

     children() Show source   
 
```
# File lib/nokogiri/xml/entity_reference.rb, line 6
def children
  # libxml2 will create a malformed child node for predefined
  # entities. because any use of that child is likely to cause a
  # segfault, we shall pretend that it doesn't exist.
  #
  # see https://github.com/sparklemotion/nokogiri/issues/1238 for details
  NodeSet.new(document)
end
```
       inspect\_attributes() Show source   
 
```
# File lib/nokogiri/xml/entity_reference.rb, line 15
def inspect_attributes
  [:name]
end
```
     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/EntityReference.html>

class Nokogiri::XML::EntityDecl
================================



Parent:
cNokogiriXmlNode
    ### Public Class Methods

     new(name, doc, \*args) Show source   
 
```
# File lib/nokogiri/xml/entity_decl.rb, line 12
def self.new(name, doc, *args)
  doc.create_entity(name, *args)
end
```
       ### Public Instance Methods

      content  Show source   
 
```
static VALUE
get_content(VALUE self)
{
  xmlEntityPtr node;
  Noko_Node_Get_Struct(self, xmlEntity, node);

  if (!node->content) { return Qnil; }

  return NOKOGIRI_STR_NEW(node->content, node->length);
}
```
  Get the content

       entity\_type  Show source   
 
```
static VALUE
entity_type(VALUE self)
{
  xmlEntityPtr node;
  Noko_Node_Get_Struct(self, xmlEntity, node);

  return INT2NUM((int)node->etype);
}
```
  Get the entity type

       external\_id  Show source   
 
```
static VALUE
external_id(VALUE self)
{
  xmlEntityPtr node;
  Noko_Node_Get_Struct(self, xmlEntity, node);

  if (!node->ExternalID) { return Qnil; }

  return NOKOGIRI_STR_NEW2(node->ExternalID);
}
```
  Get the external identifier for PUBLIC

      inspect() Show source   
 
```
# File lib/nokogiri/xml/entity_decl.rb, line 16
def inspect
  "#<#{self.class.name}:#{format("0x%x", object_id)} #{to_s.inspect}>"
end
```
        original\_content  Show source   
 
```
static VALUE
original_content(VALUE self)
{
  xmlEntityPtr node;
  Noko_Node_Get_Struct(self, xmlEntity, node);

  if (!node->orig) { return Qnil; }

  return NOKOGIRI_STR_NEW2(node->orig);
}
```
  Get the [`original_content`](entitydecl#method-i-original_content) before ref substitution

       system\_id  Show source   
 
```
static VALUE
system_id(VALUE self)
{
  xmlEntityPtr node;
  Noko_Node_Get_Struct(self, xmlEntity, node);

  if (!node->SystemID) { return Qnil; }

  return NOKOGIRI_STR_NEW2(node->SystemID);
}
```
  Get the URI for a SYSTEM or PUBLIC Entity

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/EntityDecl.html>

class Nokogiri::XML::Namespace
===============================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
Included modules:
[Nokogiri::XML::PP::Node](pp/node)
    ### Attributes

    document[R]      ### Public Instance Methods

      deconstruct\_keys(array\_of\_names) → Hash  Show source   
 
```
# File lib/nokogiri/xml/namespace.rb, line 47
def deconstruct_keys(keys)
  { prefix: prefix, href: href }
end
```
  Returns a hash describing the [`Namespace`](namespace), to use in pattern matching.

 Valid keys and their values:

 * `prefix` → (String, nil) The namespace’s prefix, or `nil` if there is no prefix (e.g., default namespace).
* `href` → (String) The namespace’s URI

 ⚡ This is an experimental feature, available since v1.14.0

 **Example**

 
```
doc = Nokogiri::XML.parse(<<~XML)
  <?xml version="1.0"?>
  <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko">
    <child1 foo="abc" noko:bar="def"/>
    <noko:child2 foo="qwe" noko:bar="rty"/>
  </root>
XML

doc.root.elements.first.namespace
# => #(Namespace:0x35c { href = "http://nokogiri.org/ns/default" })

doc.root.elements.first.namespace.deconstruct_keys([:prefix, :href])
# => {:prefix=>nil, :href=>"http://nokogiri.org/ns/default"}

doc.root.elements.last.namespace
# => #(Namespace:0x370 {
#      prefix = "noko",
#      href = "http://nokogiri.org/ns/noko"
#      })

doc.root.elements.last.namespace.deconstruct_keys([:prefix, :href])
# => {:prefix=>"noko", :href=>"http://nokogiri.org/ns/noko"}

```
       href() → String  Show source   
 
```
static VALUE
href(VALUE self)
{
  xmlNsPtr ns;

  Noko_Namespace_Get_Struct(self, xmlNs, ns);
  if (!ns->href) { return Qnil; }

  return NOKOGIRI_STR_NEW2(ns->href);
}
```
  Returns the URI reference for this [`Namespace`](namespace).

 **Example**

 
```
doc = Nokogiri::XML.parse(<<~XML)
  <?xml version="1.0"?>
  <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko">
    <child1 foo="abc" noko:bar="def"/>
    <noko:child2 foo="qwe" noko:bar="rty"/>
  </root>
XML

doc.root.elements.first.namespace.href
# => "http://nokogiri.org/ns/default"

doc.root.elements.last.namespace.href
# => "http://nokogiri.org/ns/noko"

```
       prefix() → String or nil  Show source   
 
```
static VALUE
prefix(VALUE self)
{
  xmlNsPtr ns;

  Noko_Namespace_Get_Struct(self, xmlNs, ns);
  if (!ns->prefix) { return Qnil; }

  return NOKOGIRI_STR_NEW2(ns->prefix);
}
```
  Return the prefix for this [`Namespace`](namespace), or `nil` if there is no prefix (e.g., default namespace).

 **Example**

 
```
doc = Nokogiri::XML.parse(<<~XML)
  <?xml version="1.0"?>
  <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko">
    <child1 foo="abc" noko:bar="def"/>
    <noko:child2 foo="qwe" noko:bar="rty"/>
  </root>
XML

doc.root.elements.first.namespace.prefix
# => nil

doc.root.elements.last.namespace.prefix
# => "noko"

```
    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Namespace.html>

class Nokogiri::XML::Node::SaveOptions
=======================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  Save options for serializing nodes. See the method group entitled [Serialization and Generating Output at `Node`](../node#class-Nokogiri::XML::Node-label-Serialization+and+Generating+Output) for usage.

     ### Constants

   AS\_BUILDER   Save builder created document

  AS\_HTML   Save as [`HTML`](../../html4)

  AS\_XHTML   Save as XHTML

  AS\_XML   Save as [`XML`](../../xml)

  DEFAULT\_HTML   the default for [`HTML`](../../html4) document

  DEFAULT\_XHTML   the default for XHTML document

  DEFAULT\_XML   the default for [`XML`](../../xml) documents

  FORMAT   Format serialized xml

  NO\_DECLARATION   Do not include declarations

  NO\_EMPTY\_TAGS   Do not include empty tags

  NO\_XHTML   Do not save XHTML

      ### Attributes

    options[R]   Integer representation of the [`SaveOptions`](saveoptions)

     to\_i[R]   Integer representation of the [`SaveOptions`](saveoptions)

      ### Public Class Methods

     new(options = 0) Show source   
 
```
# File lib/nokogiri/xml/node/save_options.rb, line 47
def initialize(options = 0)
  @options = options
end
```
  Create a new [`SaveOptions`](saveoptions) object with `options`

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Node/SaveOptions.html>

class Nokogiri::XML::NodeSet
=============================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
Included modules:
[Nokogiri::XML::Searchable](searchable)
  A [`NodeSet`](nodeset) contains a list of [`Nokogiri::XML::Node`](node) objects. Typically a [`NodeSet`](nodeset) is return as a result of searching a [`Document`](document) via [`Nokogiri::XML::Searchable#css`](searchable#method-i-css) or [`Nokogiri::XML::Searchable#xpath`](searchable#method-i-xpath)

     ### Constants

   LOOKS\_LIKE\_XPATH    Included from [Nokogiri::XML::Searchable](searchable)  Regular expression used by [`Searchable#search`](searchable#method-i-search) to determine if a query string is [`CSS`](../css) or [`XPath`](xpath)

      ### Attributes

    document[RW]   The [`Document`](document) this [`NodeSet`](nodeset) is associated with

      ### Public Class Methods

     new(document, list = []) { |self| ... } Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 20
def initialize(document, list = [])
  @document = document
  document.decorate(self)
  list.each { |x| self << x }
  yield self if block_given?
end
```
  Create a [`NodeSet`](nodeset) with `document` defaulting to `list`

      ### Public Instance Methods

      search \*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]     Alias for: [at](nodeset#method-i-at)       &(node\_set)  Show source   
 
```
static VALUE
intersection(VALUE self, VALUE rb_other)
{
  xmlNodeSetPtr node_set, other ;
  xmlNodeSetPtr intersection;

  if (!rb_obj_is_kind_of(rb_other, cNokogiriXmlNodeSet)) {
    rb_raise(rb_eArgError, "node_set must be a Nokogiri::XML::NodeSet");
  }

  Data_Get_Struct(self, xmlNodeSet, node_set);
  Data_Get_Struct(rb_other, xmlNodeSet, other);

  intersection = xmlXPathIntersection(node_set, other);
  return noko_xml_node_set_wrap(intersection, rb_iv_get(self, "@document"));
}
```
  Set Intersection — Returns a new [`NodeSet`](nodeset) containing nodes common to the two NodeSets.

      +(p1)    Alias for: [|](nodeset#method-i-7C)       -(node\_set)  Show source   
 
```
static VALUE
minus(VALUE self, VALUE rb_other)
{
  xmlNodeSetPtr node_set, other;
  xmlNodeSetPtr new;
  int j ;

  if (!rb_obj_is_kind_of(rb_other, cNokogiriXmlNodeSet)) {
    rb_raise(rb_eArgError, "node_set must be a Nokogiri::XML::NodeSet");
  }

  Data_Get_Struct(self, xmlNodeSet, node_set);
  Data_Get_Struct(rb_other, xmlNodeSet, other);

  new = xmlXPathNodeSetMerge(NULL, node_set);
  for (j = 0 ; j < other->nodeNr ; ++j) {
    xpath_node_set_del(new, other->nodeTab[j]);
  }

  return noko_xml_node_set_wrap(new, rb_iv_get(self, "@document"));
}
```
  Difference - returns a new [`NodeSet`](nodeset) that is a copy of this [`NodeSet`](nodeset), removing each item that also appears in `node_set`

      <<(p1)    Alias for: [push](nodeset#method-i-push)      ==(other) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 393
def ==(other)
  return false unless other.is_a?(Nokogiri::XML::NodeSet)
  return false unless length == other.length

  each_with_index do |node, i|
    return false unless node == other[i]
  end
  true
end
```
  Equality – Two NodeSets are equal if the contain the same number of elements and if each element is equal to the corresponding element in the other [`NodeSet`](nodeset)

       [index] → Node or nil  Show source    [start, length] → NodeSet or nil     [range] → NodeSet or nil    
 
```
static VALUE
slice(int argc, VALUE *argv, VALUE self)
{
  VALUE arg ;
  long beg, len ;
  xmlNodeSetPtr node_set;

  Data_Get_Struct(self, xmlNodeSet, node_set);

  if (argc == 2) {
    beg = NUM2LONG(argv[0]);
    len = NUM2LONG(argv[1]);
    if (beg < 0) {
      beg += node_set->nodeNr ;
    }
    return subseq(self, beg, len);
  }

  if (argc != 1) {
    rb_scan_args(argc, argv, "11", NULL, NULL);
  }
  arg = argv[0];

  if (FIXNUM_P(arg)) {
    return index_at(self, FIX2LONG(arg));
  }

  /* if arg is Range */
  switch (rb_range_beg_len(arg, &beg, &len, (long)node_set->nodeNr, 0)) {
    case Qfalse:
      break;
    case Qnil:
      return Qnil;
    default:
      return subseq(self, beg, len);
  }

  return index_at(self, NUM2LONG(arg));
}
```
  [`Element`](element) reference - returns the node at `index`, or returns a [`NodeSet`](nodeset) containing nodes starting at `start` and continuing for `length` elements, or returns a [`NodeSet`](nodeset) containing nodes specified by `range`. Negative `indices` count backward from the end of the `node_set` (-1 is the last node). Returns nil if the `index` (or `start`) are out of range.

   Also aliased as: [slice](nodeset#method-i-slice)      add\_class(name) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 139
def add_class(name)
  each do |el|
    el.add_class(name)
  end
  self
end
```
  Add the class attribute `name` to all [`Node`](node) objects in the [`NodeSet`](nodeset).

 See [`Nokogiri::XML::Node#add_class`](node#method-i-add_class) for more information.

      after(datum) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 69
def after(datum)
  last.after(datum)
end
```
  Insert `datum` after the last [`Node`](node) in this [`NodeSet`](nodeset)

      append\_class(name) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 151
def append_class(name)
  each do |el|
    el.append_class(name)
  end
  self
end
```
  Append the class attribute `name` to all [`Node`](node) objects in the [`NodeSet`](nodeset).

 See [`Nokogiri::XML::Node#append_class`](node#method-i-append_class) for more information.

       search \*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]  Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 119
def at(*args)
  if args.length == 1 && args.first.is_a?(Numeric)
    return self[args.first]
  end

  super(*args)
end
```
  Search this object for `paths`, and return only the first result. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries.

 See [`Searchable#search`](searchable#method-i-search) for more information.

 Or, if passed an integer, index into the NodeSet:

 
```
node_set.at(3) # same as node_set[3]

```
  Calls superclass method [`Nokogiri::XML::Searchable#at`](searchable#method-i-at)    Also aliased as: [%](nodeset#method-i-25)      attr(key, value = nil) { |node| ... } Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 203
def attr(key, value = nil, &block)
  unless key.is_a?(Hash) || (key && (value || block))
    return first&.attribute(key)
  end

  hash = key.is_a?(Hash) ? key : { key => value }

  hash.each do |k, v|
    each do |node|
      node[k] = v || yield(node)
    end
  end

  self
end
```
  Set attributes on each [`Node`](node) in the [`NodeSet`](nodeset), or get an attribute from the first [`Node`](node) in the [`NodeSet`](nodeset).

 To get an attribute from the first [`Node`](node) in a NodeSet:

 
```
node_set.attr("href") # => "https://www.nokogiri.org"

```
 Note that an empty [`NodeSet`](nodeset) will return nil when `#attr` is called as a getter.

 To set an attribute on each node, `key` can either be an attribute name, or a Hash of attribute names and values. When called as a setter, `#attr` returns the [`NodeSet`](nodeset).

 If `key` is an attribute name, then either `value` or `block` must be passed.

 If `key` is a Hash then attributes will be set for each key/value pair:

 
```
node_set.attr("href" => "https://www.nokogiri.org", "class" => "member")

```
 If `value` is passed, it will be used as the attribute value for all nodes:

 
```
node_set.attr("href", "https://www.nokogiri.org")

```
 If `block` is passed, it will be called on each [`Node`](node) object in the [`NodeSet`](nodeset) and the return value used as the attribute value for that node:

 
```
node_set.attr("class") { |node| node.name }

```
   Also aliased as: [set](nodeset#method-i-set), [attribute](nodeset#method-i-attribute)      attribute(key, value = nil, &block)    Alias for: [attr](nodeset#method-i-attr)      before(datum) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 63
def before(datum)
  first.before(datum)
end
```
  Insert `datum` before the first [`Node`](node) in this [`NodeSet`](nodeset)

      children() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 406
def children
  node_set = NodeSet.new(document)
  each do |node|
    node.children.each { |n| node_set.push(n) }
  end
  node_set
end
```
  Returns a new [`NodeSet`](nodeset) containing all the children of all the nodes in the [`NodeSet`](nodeset)

       dup     Alias for: [dup](nodeset#method-i-dup)       css \*rules, [namespace-bindings, custom-pseudo-class]  Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 83
def css(*args)
  rules, handler, ns, _ = extract_params(args)
  paths = css_rules_to_xpath(rules, ns)

  inject(NodeSet.new(document)) do |set, node|
    set + xpath_internal(node, paths, handler, ns, nil)
  end
end
```
  Search this node set for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example:

 For more information see [`Nokogiri::XML::Searchable#css`](searchable#method-i-css)

       deconstruct() → Array  Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 440
def deconstruct
  to_a
end
```
  Returns the members of this [`NodeSet`](nodeset) as an array, to use in pattern matching.

 ⚡ This is an experimental feature, available since v1.14.0

       delete(node)  Show source   
 
```
static VALUE
delete (VALUE self, VALUE rb_node)
{
  xmlNodeSetPtr node_set;
  xmlNodePtr node;

  Check_Node_Set_Node_Type(rb_node);

  Data_Get_Struct(self, xmlNodeSet, node_set);
  Noko_Node_Get_Struct(rb_node, xmlNode, node);

  if (xmlXPathNodeSetContains(node_set, node)) {
    xpath_node_set_del(node_set, node);
    return rb_node;
  }
  return Qnil ;
}
```
  Delete `node` from the Nodeset, if it is a member. Returns the deleted node if found, otherwise returns nil.

       dup  Show source   
 
```
static VALUE
duplicate(VALUE self)
{
  xmlNodeSetPtr node_set;
  xmlNodeSetPtr dupl;

  Data_Get_Struct(self, xmlNodeSet, node_set);

  dupl = xmlXPathNodeSetMerge(NULL, node_set);

  return noko_xml_node_set_wrap(dupl, rb_iv_get(self, "@document"));
}
```
  Duplicate this [`NodeSet`](nodeset). Note that the Nodes contained in the [`NodeSet`](nodeset) are not duplicated (similar to how Array and other Enumerable classes work).

   Also aliased as: [clone](nodeset#method-i-clone)      each() { |self| ... } Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 231
def each
  return to_enum unless block_given?

  0.upto(length - 1) do |x|
    yield self[x]
  end
  self
end
```
  Iterate over each node, yielding to `block`

      empty?() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 45
def empty?
  length == 0
end
```
  Is this [`NodeSet`](nodeset) empty?

      filter(expr) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 130
def filter(expr)
  find_all { |node| node.matches?(expr) }
end
```
  Filter this list for nodes that match `expr`

      first(n = nil) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 29
def first(n = nil)
  return self[0] unless n

  list = []
  [n, length].min.times { |i| list << self[i] }
  list
end
```
  Get the first element of the [`NodeSet`](nodeset).

       include?(node)  Show source   
 
```
static VALUE
include_eh(VALUE self, VALUE rb_node)
{
  xmlNodeSetPtr node_set;
  xmlNodePtr node;

  Check_Node_Set_Node_Type(rb_node);

  Data_Get_Struct(self, xmlNodeSet, node_set);
  Noko_Node_Get_Struct(rb_node, xmlNode, node);

  return (xmlXPathNodeSetContains(node_set, node) ? Qtrue : Qfalse);
}
```
  Returns true if any member of node set equals `node`.

      index(node = nil) { |member| ... } Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 51
def index(node = nil)
  if node
    warn("given block not used") if block_given?
    each_with_index { |member, j| return j if member == node }
  elsif block_given?
    each_with_index { |member, j| return j if yield(member) }
  end
  nil
end
```
  Returns the index of the first node in self that is == to `node` or meets the given block. Returns nil if no match is found.

      inner\_html(\*args) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 260
def inner_html(*args)
  collect { |j| j.inner_html(*args) }.join("")
end
```
  Get the inner html of all contained [`Node`](node) objects

      inner\_text() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 253
def inner_text
  collect(&:inner_text).join("")
end
```
  Get the inner text of all contained [`Node`](node) objects

 Note: This joins the text of all [`Node`](node) objects in the NodeSet:

 
```
doc = Nokogiri::XML('<xml><a><d>foo</d><d>bar</d></a></xml>')
doc.css('d').text # => "foobar"

```
 Instead, if you want to return the text of all nodes in the NodeSet:

 
```
doc.css('d').map(&:text) # => ["foo", "bar"]

```
 See [`Nokogiri::XML::Node#content`](node#method-i-content) for more information.

   Also aliased as: [text](nodeset#method-i-text)      inspect() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 427
def inspect
  "[#{map(&:inspect).join(", ")}]"
end
```
  Return a nicely formated string representation

      last() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 39
def last
  self[-1]
end
```
  Get the last element of the [`NodeSet`](nodeset).

       length  Show source   
 
```
static VALUE
length(VALUE self)
{
  xmlNodeSetPtr node_set;

  Data_Get_Struct(self, xmlNodeSet, node_set);

  return node_set ? INT2NUM(node_set->nodeNr) : INT2NUM(0);
}
```
  Get the length of the node set

   Also aliased as: [size](nodeset#method-i-size)      pop() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 374
def pop
  return nil if length == 0

  delete(last)
end
```
  Removes the last element from set and returns it, or `nil` if the set is empty

       push(node)  Show source   
 
```
static VALUE
push(VALUE self, VALUE rb_node)
{
  xmlNodeSetPtr node_set;
  xmlNodePtr node;

  Check_Node_Set_Node_Type(rb_node);

  Data_Get_Struct(self, xmlNodeSet, node_set);
  Noko_Node_Get_Struct(rb_node, xmlNode, node);

  xmlXPathNodeSetAdd(node_set, node);

  return self;
}
```
  Append `node` to the [`NodeSet`](nodeset).

   Also aliased as: [<<](nodeset#method-i-3C-3C)       unlink     Alias for: [unlink](nodeset#method-i-unlink)      remove\_attr(name) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 223
def remove_attr(name)
  each { |el| el.delete(name) }
  self
end
```
  Remove the attributed named `name` from all [`Node`](node) objects in the [`NodeSet`](nodeset)

   Also aliased as: [remove\_attribute](nodeset#method-i-remove_attribute)      remove\_attribute(name)    Alias for: [remove\_attr](nodeset#method-i-remove_attr)      remove\_class(name = nil) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 163
def remove_class(name = nil)
  each do |el|
    el.remove_class(name)
  end
  self
end
```
  Remove the class attribute `name` from all [`Node`](node) objects in the [`NodeSet`](nodeset).

 See [`Nokogiri::XML::Node#remove_class`](node#method-i-remove_class) for more information.

      reverse() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 417
def reverse
  node_set = NodeSet.new(document)
  (length - 1).downto(0) do |x|
    node_set.push(self[x])
  end
  node_set
end
```
  Returns a new [`NodeSet`](nodeset) containing all the nodes in the [`NodeSet`](nodeset) in reverse order

      set(key, value = nil, &block)    Alias for: [attr](nodeset#method-i-attr)      shift() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 383
def shift
  return nil if length == 0

  delete(first)
end
```
  Returns the first element of the [`NodeSet`](nodeset) and removes it. Returns `nil` if the set is empty.

       length     Alias for: [length](nodeset#method-i-length)       slice(index) → Node or nil     slice(start, length) → NodeSet or nil     slice(range) → NodeSet or nil     [`Element`](element) reference - returns the node at `index`, or returns a [`NodeSet`](nodeset) containing nodes starting at `start` and continuing for `length` elements, or returns a [`NodeSet`](nodeset) containing nodes specified by `range`. Negative `indices` count backward from the end of the `node_set` (-1 is the last node). Returns nil if the `index` (or `start`) are out of range.

   Alias for: [[]](nodeset#method-i-5B-5D)      text()    Alias for: [inner\_text](nodeset#method-i-inner_text)       to\_a  Show source   
 
```
static VALUE
to_array(VALUE self)
{
  xmlNodeSetPtr node_set ;
  VALUE list;
  int i;

  Data_Get_Struct(self, xmlNodeSet, node_set);

  list = rb_ary_new2(node_set->nodeNr);
  for (i = 0; i < node_set->nodeNr; i++) {
    VALUE elt = noko_xml_node_wrap_node_set_result(node_set->nodeTab[i], self);
    rb_ary_push(list, elt);
  }

  return list;
}
```
  Return this list as an Array

   Also aliased as: [to\_ary](nodeset#method-i-to_ary)       to\_a     Alias for: [to\_a](nodeset#method-i-to_a)      to\_html(\*args) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 341
def to_html(*args)
  if Nokogiri.jruby?
    options = args.first.is_a?(Hash) ? args.shift : {}
    options[:save_with] ||= Node::SaveOptions::DEFAULT_HTML
    args.insert(0, options)
  end
  if empty?
    encoding = (args.first.is_a?(Hash) ? args.first[:encoding] : nil)
    encoding ||= document.encoding
    encoding.nil? ? "" : "".encode(encoding)
  else
    map { |x| x.to_html(*args) }.join
  end
end
```
  Convert this [`NodeSet`](nodeset) to [`HTML`](../html4)

      to\_s() Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 335
def to_s
  map(&:to_s).join
end
```
  Convert this [`NodeSet`](nodeset) to a string.

      to\_xhtml(\*args) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 358
def to_xhtml(*args)
  map { |x| x.to_xhtml(*args) }.join
end
```
  Convert this [`NodeSet`](nodeset) to XHTML

      to\_xml(\*args) Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 364
def to_xml(*args)
  map { |x| x.to_xml(*args) }.join
end
```
  Convert this [`NodeSet`](nodeset) to [`XML`](../xml)

       unlink  Show source   
 
```
static VALUE
unlink_nodeset(VALUE self)
{
  xmlNodeSetPtr node_set;
  int j, nodeNr ;

  Data_Get_Struct(self, xmlNodeSet, node_set);

  nodeNr = node_set->nodeNr ;
  for (j = 0 ; j < nodeNr ; j++) {
    if (! NOKOGIRI_NAMESPACE_EH(node_set->nodeTab[j])) {
      VALUE node ;
      xmlNodePtr node_ptr;
      node = noko_xml_node_wrap(Qnil, node_set->nodeTab[j]);
      rb_funcall(node, rb_intern("unlink"), 0); /* modifies the C struct out from under the object */
      Noko_Node_Get_Struct(node, xmlNode, node_ptr);
      node_set->nodeTab[j] = node_ptr ;
    }
  }
  return self ;
}
```
  Unlink this [`NodeSet`](nodeset) and all [`Node`](node) objects it contains from their current context.

   Also aliased as: [remove](nodeset#method-i-remove)       wrap(markup) → self  Show source    wrap(node) → self    
 
```
# File lib/nokogiri/xml/node_set.rb, line 328
def wrap(node_or_tags)
  map { |node| node.wrap(node_or_tags) }
  self
end
```
  Wrap each member of this [`NodeSet`](nodeset) with the node parsed from `markup` or a dup of the `node`.

  Parameters   * **markup** (String) Markup that is parsed, once per member of the [`NodeSet`](nodeset), and used as the wrapper. Each node’s parent, if it exists, is used as the context node for parsing; otherwise the associated document is used. If the parsed fragment has multiple roots, the first root node is used as the wrapper.
* **node** ([`Nokogiri::XML::Node`](node)) An element that is ‘#dup`ed and used as the wrapper.

  Returns   `self`, to support chaining.

   ⚠ Note that if a `String` is passed, the markup will be parsed **once per node** in the [`NodeSet`](nodeset). You can avoid this overhead in cases where you know exactly the wrapper you wish to use by passing a `Node` instead.

 Also see [`Node#wrap`](node#method-i-wrap)

 **Example** with a `String` argument:

 
```
doc = Nokogiri::HTML5(<<~HTML)
  <html><body>
    <a>a</a>
    <a>b</a>
    <a>c</a>
    <a>d</a>
  </body></html>
HTML
doc.css("a").wrap("<div></div>")
doc.to_html
# => <html><head></head><body>
#      <div><a>a</a></div>
#      <div><a>b</a></div>
#      <div><a>c</a></div>
#      <div><a>d</a></div>
#    </body></html>

```
 **Example** with a `Node` argument

 💡 Note that this is faster than the equivalent call passing a `String` because it avoids having to reparse the wrapper markup for each node.

 
```
doc = Nokogiri::HTML5(<<~HTML)
  <html><body>
    <a>a</a>
    <a>b</a>
    <a>c</a>
    <a>d</a>
  </body></html>
HTML
doc.css("a").wrap(doc.create_element("div"))
doc.to_html
# => <html><head></head><body>
#      <div><a>a</a></div>
#      <div><a>b</a></div>
#      <div><a>c</a></div>
#      <div><a>d</a></div>
#    </body></html>

```
       xpath \*paths, [namespace-bindings, variable-bindings, custom-handler-class]  Show source   
 
```
# File lib/nokogiri/xml/node_set.rb, line 99
def xpath(*args)
  paths, handler, ns, binds = extract_params(args)

  inject(NodeSet.new(document)) do |set, node|
    set + xpath_internal(node, paths, handler, ns, binds)
  end
end
```
  Search this node set for [`XPath`](xpath) `paths`. `paths` must be one or more [`XPath`](xpath) queries.

 For more information see [`Nokogiri::XML::Searchable#xpath`](searchable#method-i-xpath)

       |(node\_set)  Show source   
 
```
static VALUE
rb_xml_node_set_union(VALUE rb_node_set, VALUE rb_other)
{
  xmlNodeSetPtr c_node_set, c_other;
  xmlNodeSetPtr c_new_node_set;

  if (!rb_obj_is_kind_of(rb_other, cNokogiriXmlNodeSet)) {
    rb_raise(rb_eArgError, "node_set must be a Nokogiri::XML::NodeSet");
  }

  Data_Get_Struct(rb_node_set, xmlNodeSet, c_node_set);
  Data_Get_Struct(rb_other, xmlNodeSet, c_other);

  c_new_node_set = xmlXPathNodeSetMerge(NULL, c_node_set);
  c_new_node_set = xmlXPathNodeSetMerge(c_new_node_set, c_other);

  return noko_xml_node_set_wrap(c_new_node_set, rb_iv_get(rb_node_set, "@document"));
}
```
  Returns a new set built by merging the set and the elements of the given set.

   Also aliased as: [+](nodeset#method-i-2B)        Searching via XPath or CSS Queries
-----------------------------------

  [↑ top](#top)     ### Public Instance Methods

     /(\*args)     Included from [Nokogiri::XML::Searchable](searchable)    Alias for: [search](searchable#method-i-search)       >(selector) → NodeSet  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 196
def >(selector) # rubocop:disable Naming/BinaryOperatorParameterName
  ns = (document.root&.namespaces || {})
  xpath(CSS.xpath_for(selector, prefix: "./", ns: ns).first)
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this node’s immediate children using [`CSS`](../css) selector `selector`

       at\_css(\*rules, [namespace-bindings, custom-pseudo-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 140
def at_css(*args)
  css(*args).first
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this object for [`CSS`](../css) `rules`, and return only the first match. `rules` must be one or more [`CSS`](../css) selectors.

 See [`Searchable#css`](searchable#method-i-css) for more information.

       at\_xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 188
def at_xpath(*args)
  xpath(*args).first
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this node for [`XPath`](xpath) `paths`, and return only the first match. `paths` must be one or more [`XPath`](xpath) queries.

 See [`Searchable#xpath`](searchable#method-i-xpath) for more information.

       search(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 51
def search(*args)
  paths, handler, ns, binds = extract_params(args)

  xpaths = paths.map(&:to_s).map do |path|
    LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns)
  end.flatten.uniq

  xpath(*(xpaths + [ns, handler, binds].compact))
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this object for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries:

 
```
node.search("div.employee", ".//title")

```
 A hash of namespace bindings may be appended:

 
```
node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'})
node.search('bike|tire', {'bike' => 'http://schwinn.com/'})

```
 For [`XPath`](xpath) queries, a hash of variable bindings may also be appended to the namespace bindings. For example:

 
```
node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'})

```
 💡 Custom [`XPath`](xpath) functions and [`CSS`](../css) pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

 
```
handler = Class.new {
  def regex node_set, regex
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler)

```
 See [`Searchable#xpath`](searchable#method-i-xpath) and [`Searchable#css`](searchable#method-i-css) for further usage help.

   Also aliased as: [/](searchable#method-i-2F)    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/NodeSet.html>

class Nokogiri::XML::Notation
==============================



Parent:
Struct.new(:name, :public\_id, :system\_id)
  Struct representing an [XML Schema Notation](https://www.w3.org/TR/xml/#Notations)

     ### Attributes

    name[RW]   The name for the element.

     public\_id[RW]   The URI corresponding to the public identifier

     system\_id[RW]   The URI corresponding to the system identifier

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Notation.html>

class Nokogiri::XML::Node
==========================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
Included modules:

[Nokogiri::XML::PP::Node](pp/node), [Nokogiri::XML::Searchable](searchable), [Nokogiri::ClassResolver](../classresolver)

  [`Nokogiri::XML::Node`](node) is the primary API you’ll use to interact with your [`Document`](document).

 Attributes
----------

 A [`Nokogiri::XML::Node`](node) may be treated similarly to a hash with regard to attributes. For example:

 
```
node = Nokogiri::XML::DocumentFragment.parse("<a href='#foo' id='link'>link</a>").at_css("a")
node.to_html # => "<a href=\"#foo\" id=\"link\">link</a>"
node['href'] # => "#foo"
node.keys # => ["href", "id"]
node.values # => ["#foo", "link"]
node['class'] = 'green' # => "green"
node.to_html # => "<a href=\"#foo\" id=\"link\" class=\"green\">link</a>"

```
 See the method group entitled [Working With Node Attributes at `Node`](node#class-Nokogiri::XML::Node-label-Working+With+Node+Attributes) for the full set of methods.

 Navigation
----------

 [`Nokogiri::XML::Node`](node) also has methods that let you move around your tree:

   [`#parent`](node#method-i-parent), [`#children`](node#method-i-children), [`#next`](node#method-i-next), [`#previous`](node#method-i-previous)   Navigate up, down, or through siblings.

   See the method group entitled [Traversing Document Structure at `Node`](node#class-Nokogiri::XML::Node-label-Traversing+Document+Structure) for the full set of methods.

 Serialization
-------------

 When printing or otherwise emitting a document or a node (and its subtree), there are a few methods you might want to use:

   [`#content`](node#method-i-content), [`#text`](node#method-i-text), [`#inner_text`](node#method-i-inner_text), [`#to_str`](node#method-i-to_str)   These methods will all \*\*emit plaintext\*\*, meaning that entities will be replaced (e.g., +&lt;+ will be replaced with +<+), meaning that any sanitizing will likely be un-done in the output.

   [`#to_s`](node#method-i-to_s), [`#to_xml`](node#method-i-to_xml), [`#to_html`](node#method-i-to_html), [`#inner_html`](node#method-i-inner_html)   These methods will all \*\*emit properly-escaped markup\*\*, meaning that it’s suitable for consumption by browsers, parsers, etc.

   See the method group entitled [Serialization and Generating Output at `Node`](node#class-Nokogiri::XML::Node-label-Serialization+and+Generating+Output) for the full set of methods.

 Searching
---------

 You may search this node’s subtree using methods like [`#xpath`](node#method-i-xpath) and [`#css`](node#method-i-css).

 See the method group entitled [Searching via XPath or CSS Queries at `Node`](node#class-Nokogiri::XML::Node-label-Searching+via+XPath+or+CSS+Queries) for the full set of methods.

     ### Constants

   ATTRIBUTE\_DECL   Attribute declaration type

  ATTRIBUTE\_NODE   Attribute node type

  CDATA\_SECTION\_NODE   [`CDATA`](cdata) node type, see [`Nokogiri::XML::Node#cdata?`](node#method-i-cdata-3F)

  COMMENT\_NODE   [`Comment`](comment) node type, see [`Nokogiri::XML::Node#comment?`](node#method-i-comment-3F)

  DOCB\_DOCUMENT\_NODE   DOCB document node type

  DOCUMENT\_FRAG\_NODE   [`Document`](document) fragment node type

  DOCUMENT\_NODE   [`Document`](document) node type, see [`Nokogiri::XML::Node#xml?`](node#method-i-xml-3F)

  DOCUMENT\_TYPE\_NODE   [`Document`](document) type node type

  DTD\_NODE   [`DTD`](dtd) node type

  ELEMENT\_DECL   [`Element`](element) declaration type

  ELEMENT\_NODE   [`Element`](element) node type, see [`Nokogiri::XML::Node#element?`](node#method-i-element-3F)

  ENTITY\_DECL   Entity declaration type

  ENTITY\_NODE   Entity node type

  ENTITY\_REF\_NODE   Entity reference node type

  HTML\_DOCUMENT\_NODE   [`HTML`](../html4) document node type, see [`Nokogiri::XML::Node#html?`](node#method-i-html-3F)

  IMPLIED\_XPATH\_CONTEXTS  LOOKS\_LIKE\_XPATH    Included from [Nokogiri::XML::Searchable](searchable)  Regular expression used by [`Searchable#search`](searchable#method-i-search) to determine if a query string is [`CSS`](../css) or [`XPath`](xpath)

  NAMESPACE\_DECL   [`Namespace`](namespace) declaration type

  NOTATION\_NODE   [`Notation`](notation) node type

  PI\_NODE   PI node type

  TEXT\_NODE   [`Text`](text) node type, see [`Nokogiri::XML::Node#text?`](node#method-i-text-3F)

  VALID\_NAMESPACES    Included from [Nokogiri::ClassResolver](../classresolver)  [`related_class`](node#method-i-related_class) restricts matching namespaces to those matching this set.

  XINCLUDE\_END   XInclude end type

  XINCLUDE\_START   XInclude start type

      ### Public Class Methods

      new(name, document) → Nokogiri::XML::Node  Show source    new(name, document) { |node| ... } → Nokogiri::XML::Node    
 
```
# File lib/nokogiri/xml/node.rb, line 126
def initialize(name, document)
  # This is intentionally empty, and sets the method signature for subclasses.
end
```
  Create a new node with `name` that belongs to `document`.

 If you intend to add a node to a document tree, it’s likely that you will prefer one of the [`Nokogiri::XML::Node`](node) methods like [`#add_child`](node#method-i-add_child), [`#add_next_sibling`](node#method-i-add_next_sibling), [`#replace`](node#method-i-replace), etc. which will both create an element (or subtree) and place it in the document tree.

 Another alternative, if you are concerned about performance, is Nokogiri::XML::Document#create\_element which accepts additional arguments for contents or attributes but (like this method) avoids parsing markup.

  Parameters   * `name` (String)
* `document` ([`Nokogiri::XML::Document`](document)) The document to which the the returned node will belong.

  Yields   [`Nokogiri::XML::Node`](node)

  Returns   [`Nokogiri::XML::Node`](node)

        ### Public Instance Methods

     <=>(other) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1256
def <=>(other)
  return nil unless other.is_a?(Nokogiri::XML::Node)
  return nil unless document == other.document

  compare(other)
end
```
  Compare two [`Node`](node) objects with respect to their [`Document`](document). Nodes from different documents cannot be compared.

      ==(other) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1246
def ==(other)
  return false unless other
  return false unless other.respond_to?(:pointer_id)

  pointer_id == other.pointer_id
end
```
  Test to see if this [`Node`](node) is equal to `other`

      accept(visitor) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1240
def accept(visitor)
  visitor.visit(self)
end
```
  Accept a visitor. This method calls “visit” on `visitor` with self.

      ancestors(selector = nil) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1209
def ancestors(selector = nil)
  return NodeSet.new(document) unless respond_to?(:parent)
  return NodeSet.new(document) unless parent

  parents = [parent]

  while parents.last.respond_to?(:parent)
    break unless (ctx_parent = parents.last.parent)

    parents << ctx_parent
  end

  return NodeSet.new(document, parents) unless selector

  root = parents.last
  search_results = root.search(selector)

  NodeSet.new(document, parents.find_all do |parent|
    search_results.include?(parent)
  end)
end
```
  Get a list of ancestor [`Node`](node) for this [`Node`](node). If `selector` is given, the ancestors must match `selector`

       blank? → Boolean  Show source   
 
```
static VALUE
rb_xml_node_blank_eh(VALUE self)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  return (1 == xmlIsBlankNode(node)) ? Qtrue : Qfalse ;
}
```
   Returns   `true` if the node is an empty or whitespace-only text or cdata node, else `false`.

   **Example:**

 
```
Nokogiri("<root><child/></root>").root.child.blank? # => false
Nokogiri("<root>\t \n</root>").root.child.blank? # => true
Nokogiri("<root><![CDATA[\t \n]]></root>").root.child.blank? # => true
Nokogiri("<root>not-blank</root>").root.child
  .tap { |n| n.content = "" }.blank # => true

```
      cdata?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1130
def cdata?
  type == CDATA_SECTION_NODE
end
```
  Returns true if this is a [`CDATA`](cdata)

      clone(p1 = v1, p2 = v2)    Alias for: [dup](node#method-i-dup)      comment?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1125
def comment?
  type == COMMENT_NODE
end
```
  Returns true if this is a [`Comment`](comment)

       content() → String  Show source   
 
```
static VALUE
rb_xml_node_content(VALUE self)
{
  xmlNodePtr node;
  xmlChar *content;

  Noko_Node_Get_Struct(self, xmlNode, node);

  content = xmlNodeGetContent(node);
  if (content) {
    VALUE rval = NOKOGIRI_STR_NEW2(content);
    xmlFree(content);
    return rval;
  }
  return Qnil;
}
```
   Returns   Contents of all the text nodes in this node’s subtree, concatenated together into a single String.

   ⚠ Note that entities will *always* be expanded in the returned String.

 See related: [`#inner_html`](node#method-i-inner_html)

 **Example** of how entities are handled:

 Note that `&lt;` becomes `<` in the returned String.

 
```
doc = Nokogiri::XML.fragment("<child>a &lt; b</child>")
doc.at_css("child").content
# => "a < b"

```
 **Example** of how a subtree is handled:

 Note that the `<span>` tags are omitted and only the text node contents are returned, concatenated into a single string.

 
```
doc = Nokogiri::XML.fragment("<child><span>first</span> <span>second</span></child>")
doc.at_css("child").content
# => "first second"

```
   Also aliased as: [inner\_text](node#method-i-inner_text), [text](node#method-i-text), [to\_str](node#method-i-to_str)       create\_external\_subset(name, external\_id, system\_id)  Show source   
 
```
static VALUE
create_external_subset(VALUE self, VALUE name, VALUE external_id, VALUE system_id)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Noko_Node_Get_Struct(self, xmlNode, node);

  doc = node->doc;

  if (doc->extSubset) {
    rb_raise(rb_eRuntimeError, "Document already has an external subset");
  }

  dtd = xmlNewDtd(
          doc,
          NIL_P(name)        ? NULL : (const xmlChar *)StringValueCStr(name),
          NIL_P(external_id) ? NULL : (const xmlChar *)StringValueCStr(external_id),
          NIL_P(system_id)   ? NULL : (const xmlChar *)StringValueCStr(system_id)
        );

  if (!dtd) { return Qnil; }

  return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd);
}
```
  Create an external subset

       create\_internal\_subset(name, external\_id, system\_id)  Show source   
 
```
static VALUE
create_internal_subset(VALUE self, VALUE name, VALUE external_id, VALUE system_id)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Noko_Node_Get_Struct(self, xmlNode, node);

  doc = node->doc;

  if (xmlGetIntSubset(doc)) {
    rb_raise(rb_eRuntimeError, "Document already has an internal subset");
  }

  dtd = xmlCreateIntSubset(
          doc,
          NIL_P(name)        ? NULL : (const xmlChar *)StringValueCStr(name),
          NIL_P(external_id) ? NULL : (const xmlChar *)StringValueCStr(external_id),
          NIL_P(system_id)   ? NULL : (const xmlChar *)StringValueCStr(system_id)
        );

  if (!dtd) { return Qnil; }

  return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd);
}
```
  Create the internal subset of a document.

 
```
doc.create_internal_subset("chapter", "-//OASIS//DTD DocBook XML//EN", "chapter.dtd")
# => <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML//EN" "chapter.dtd">

doc.create_internal_subset("chapter", nil, "chapter.dtd")
# => <!DOCTYPE chapter SYSTEM "chapter.dtd">

```
      css\_path() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1200
def css_path
  path.split(%r{/}).filter_map do |part|
    part.empty? ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
  end.join(" > ")
end
```
  Get the path to this node as a [`CSS`](../css) expression

      decorate!() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 132
def decorate!
  document.decorate(self)
end
```
  Decorate this node with the decorators set up in this node’s [`Document`](document)

      description() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1167
def description
  return nil if document.xml?

  Nokogiri::HTML4::ElementDescription[name]
end
```
  Fetch the [`Nokogiri::HTML4::ElementDescription`](../html4/elementdescription) for this node. Returns nil on [`XML`](../xml) documents and on unknown tags.

      document?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1145
def document?
  is_a?(XML::Document)
end
```
  Returns true if this is a [`Document`](document)

       dup → Nokogiri::XML::Node  Show source    dup(depth) → Nokogiri::XML::Node     dup(depth, new\_parent\_doc) → Nokogiri::XML::Node    
 
```
static VALUE
duplicate_node(int argc, VALUE *argv, VALUE self)
{
  VALUE r_level, r_new_parent_doc;
  int level;
  int n_args;
  xmlDocPtr new_parent_doc;
  xmlNodePtr node, dup;

  Noko_Node_Get_Struct(self, xmlNode, node);

  n_args = rb_scan_args(argc, argv, "02", &r_level, &r_new_parent_doc);

  if (n_args < 1) {
    r_level = INT2NUM((long)1);
  }
  level = (int)NUM2INT(r_level);

  if (n_args < 2) {
    new_parent_doc = node->doc;
  } else {
    Data_Get_Struct(r_new_parent_doc, xmlDoc, new_parent_doc);
  }

  dup = xmlDocCopyNode(node, new_parent_doc, level);
  if (dup == NULL) { return Qnil; }

  noko_xml_document_pin_node(dup);

  return noko_xml_node_wrap(rb_obj_class(self), dup);
}
```
  Copy this node.

  Parameters   * `depth` 0 is a shallow copy, 1 (the default) is a deep copy.
* `new_parent_doc` The new node’s parent [`Document`](document). Defaults to the this node’s document.

  Returns   The new Nokgiri::XML::Node

     Also aliased as: [clone](node#method-i-clone)      elem?()    Alias for: [element?](node#method-i-element-3F)      element?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1181
def element?
  type == ELEMENT_NODE
end
```
  Returns true if this is an [`Element`](element) node

   Also aliased as: [elem?](node#method-i-elem-3F)       element\_children() → NodeSet  Show source   
 
```
static VALUE
rb_xml_node_element_children(VALUE self)
{
  xmlNodePtr node;
  xmlNodePtr child;
  xmlNodeSetPtr set;
  VALUE document;
  VALUE node_set;

  Noko_Node_Get_Struct(self, xmlNode, node);

  child = xmlFirstElementChild(node);
  set = xmlXPathNodeSetCreate(child);

  document = DOC_RUBY_OBJECT(node->doc);

  if (!child) { return noko_xml_node_set_wrap(set, document); }

  child = xmlNextElementSibling(child);
  while (NULL != child) {
    xmlXPathNodeSetAddUnique(set, child);
    child = xmlNextElementSibling(child);
  }

  node_set = noko_xml_node_set_wrap(set, document);

  return node_set;
}
```
   Returns   The node’s child elements as a [`NodeSet`](nodeset). Only children that are elements will be returned, which notably excludes [`Text`](text) nodes.

   **Example:**

 Note that [`#children`](node#method-i-children) returns the [`Text`](text) node “hello” while [`#element_children`](node#method-i-element_children) does not.

 
```
div = Nokogiri::HTML5("<div>hello<span>world</span>").at_css("div")
div.element_children
# => [#<Nokogiri::XML::Element:0x50 name="span" children=[#<Nokogiri::XML::Text:0x3c "world">]>]
div.children
# => [#<Nokogiri::XML::Text:0x64 "hello">,
#     #<Nokogiri::XML::Element:0x50 name="span" children=[#<Nokogiri::XML::Text:0x3c "world">]>]

```
   Also aliased as: [elements](node#method-i-elements)       elements() → NodeSet     Alias for: [element\_children](node#method-i-element_children)       encode\_special\_chars(string) → String  Show source   
 
```
static VALUE
encode_special_chars(VALUE self, VALUE string)
{
  xmlNodePtr node;
  xmlChar *encoded;
  VALUE encoded_str;

  Noko_Node_Get_Struct(self, xmlNode, node);
  encoded = xmlEncodeSpecialChars(
              node->doc,
              (const xmlChar *)StringValueCStr(string)
            );

  encoded_str = NOKOGIRI_STR_NEW2(encoded);
  xmlFree(encoded);

  return encoded_str;
}
```
  Encode any special characters in `string`

       external\_subset()  Show source   
 
```
static VALUE
external_subset(VALUE self)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Noko_Node_Get_Struct(self, xmlNode, node);

  if (!node->doc) { return Qnil; }

  doc = node->doc;
  dtd = doc->extSubset;

  if (!dtd) { return Qnil; }

  return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd);
}
```
  Get the external subset

       first\_element\_child() → Node  Show source   
 
```
static VALUE
rb_xml_node_first_element_child(VALUE self)
{
  xmlNodePtr node, child;
  Noko_Node_Get_Struct(self, xmlNode, node);

  child = xmlFirstElementChild(node);
  if (!child) { return Qnil; }

  return noko_xml_node_wrap(Qnil, child);
}
```
   Returns   The first child [`Node`](node) that is an element.

   **Example:**

 Note that the “hello” child, which is a [`Text`](text) node, is skipped and the `<span>` element is returned.

 
```
div = Nokogiri::HTML5("<div>hello<span>world</span>").at_css("div")
div.first_element_child
# => #(Element:0x3c { name = "span", children = [ #(Text "world")] })

```
      fragment(tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1022
def fragment(tags)
  document.related_class("DocumentFragment").new(document, tags, self)
end
```
  Create a [`DocumentFragment`](documentfragment) containing `tags` that is relative to *this* context node.

      fragment?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1160
def fragment?
  type == DOCUMENT_FRAG_NODE
end
```
  Returns true if this is a [`DocumentFragment`](documentfragment)

      html?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1140
def html?
  type == HTML_DOCUMENT_NODE
end
```
  Returns true if this is an [`HTML4::Document`](../html4/document) or [`HTML5::Document`](../html5/document) node

      inner\_html(\*args) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1195
def inner_html(*args)
  children.map { |x| x.to_html(*args) }.join
end
```
  Get the [`inner_html`](node#method-i-inner_html) for this node’s [`Node#children`](node#method-i-children)

      inner\_text()    Alias for: [content](node#method-i-content)       internal\_subset()  Show source   
 
```
static VALUE
internal_subset(VALUE self)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Noko_Node_Get_Struct(self, xmlNode, node);

  if (!node->doc) { return Qnil; }

  doc = node->doc;
  dtd = xmlGetIntSubset(doc);

  if (!dtd) { return Qnil; }

  return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd);
}
```
  Get the internal subset

       key?(attribute)  Show source   
 
```
static VALUE
key_eh(VALUE self, VALUE attribute)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  if (xmlHasProp(node, (xmlChar *)StringValueCStr(attribute))) {
    return Qtrue;
  }
  return Qfalse;
}
```
  Returns true if `attribute` is set

   Also aliased as: [has\_attribute?](node#method-i-has_attribute-3F)       lang  Show source   
 
```
static VALUE
get_lang(VALUE self_rb)
{
  xmlNodePtr self ;
  xmlChar *lang ;
  VALUE lang_rb ;

  Noko_Node_Get_Struct(self_rb, xmlNode, self);

  lang = xmlNodeGetLang(self);
  if (lang) {
    lang_rb = NOKOGIRI_STR_NEW2(lang);
    xmlFree(lang);
    return lang_rb ;
  }

  return Qnil ;
}
```
  Searches the language of a node, i.e. the values of the xml:lang attribute or the one carried by the nearest ancestor.

       lang=  Show source   
 
```
static VALUE
set_lang(VALUE self_rb, VALUE lang_rb)
{
  xmlNodePtr self ;
  xmlChar *lang ;

  Noko_Node_Get_Struct(self_rb, xmlNode, self);
  lang = (xmlChar *)StringValueCStr(lang_rb);

  xmlNodeSetLang(self, lang);

  return Qnil ;
}
```
  Set the language of a node, i.e. the values of the xml:lang attribute.

       last\_element\_child() → Node  Show source   
 
```
static VALUE
rb_xml_node_last_element_child(VALUE self)
{
  xmlNodePtr node, child;
  Noko_Node_Get_Struct(self, xmlNode, node);

  child = xmlLastElementChild(node);
  if (!child) { return Qnil; }

  return noko_xml_node_wrap(Qnil, child);
}
```
   Returns   The last child [`Node`](node) that is an element.

   **Example:**

 Note that the “hello” child, which is a [`Text`](text) node, is skipped and the `<span>yes</span>` element is returned.

 
```
div = Nokogiri::HTML5("<div><span>no</span><span>yes</span>skip</div>").at_css("div")
div.last_element_child
# => #(Element:0x3c { name = "span", children = [ #(Text "yes")] })

```
       line() → Integer  Show source   
 
```
static VALUE
rb_xml_node_line(VALUE rb_node)
{
  xmlNodePtr c_node;
  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  return LONG2NUM(xmlGetLineNo(c_node));
}
```
   Returns   The line number of this [`Node`](node).

    **⚠ The CRuby and JRuby implementations differ in important ways!** 

 Semantic differences:

 * The CRuby method reflects the node’s line number *in the parsed string*
* The JRuby method reflects the node’s line number *in the final DOM structure* after corrections have been applied

 Performance differences:

 * The CRuby method is [O(1)](https://en.wikipedia.org/wiki/Time_complexity#Constant_time) (constant time)
* The JRuby method is [O(n)](https://en.wikipedia.org/wiki/Time_complexity#Linear_time) (linear time, where n is the number of nodes before/above the element in the DOM)

 If you’d like to help improve the JRuby implementation, please review these issues and reach out to the maintainers:

 * [github.com/sparklemotion/nokogiri/issues/1223](https://github.com/sparklemotion/nokogiri/issues/1223)
* [github.com/sparklemotion/nokogiri/pull/2177](https://github.com/sparklemotion/nokogiri/pull/2177)
* [github.com/sparklemotion/nokogiri/issues/2380](https://github.com/sparklemotion/nokogiri/issues/2380)

       line=(num)  Show source   
 
```
static VALUE
rb_xml_node_line_set(VALUE rb_node, VALUE rb_line_number)
{
  xmlNodePtr c_node;
  int line_number = NUM2INT(rb_line_number);

  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  // libxml2 optionally uses xmlNode.psvi to store longer line numbers, but only for text nodes.
  // search for "psvi" in SAX2.c and tree.c to learn more.
  if (line_number < 65535) {
    c_node->line = (short) line_number;
  } else {
    c_node->line = 65535;
    if (c_node->type == XML_TEXT_NODE) {
      c_node->psvi = (void *)(ptrdiff_t) line_number;
    }
  }

  return rb_line_number;
}
```
  Sets the line for this [`Node`](node). num must be less than 65535.

      matches?(selector) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1015
def matches?(selector)
  ancestors.last.search(selector).include?(self)
end
```
  Returns true if this [`Node`](node) matches `selector`

       name     Alias for: [node\_name](node#method-i-node_name)       namespace() → Namespace  Show source   
 
```
static VALUE
rb_xml_node_namespace(VALUE rb_node)
{
  xmlNodePtr c_node ;
  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  if (c_node->ns) {
    return noko_xml_namespace_wrap(c_node->ns, c_node->doc);
  }

  return Qnil ;
}
```
   Returns   The [`Namespace`](namespace) of the element or attribute node, or `nil` if there is no namespace.

   **Example:**

 
```
doc = Nokogiri::XML(<<~EOF)
  <root>
    <first/>
    <second xmlns="http://example.com/child"/>
    <foo:third xmlns:foo="http://example.com/foo"/>
  </root>
EOF
doc.at_xpath("//first").namespace
# => nil
doc.at_xpath("//xmlns:second", "xmlns" => "http://example.com/child").namespace
# => #(Namespace:0x3c { href = "http://example.com/child" })
doc.at_xpath("//foo:third", "foo" => "http://example.com/foo").namespace
# => #(Namespace:0x50 { prefix = "foo", href = "http://example.com/foo" })

```
       namespace\_definitions() → Array<Nokogiri::XML::Namespace>  Show source   
 
```
static VALUE
namespace_definitions(VALUE rb_node)
{
  /* this code in the mode of xmlHasProp() */
  xmlNodePtr c_node ;
  xmlNsPtr c_namespace;
  VALUE definitions = rb_ary_new();

  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  c_namespace = c_node->nsDef;
  if (!c_namespace) {
    return definitions;
  }

  while (c_namespace != NULL) {
    rb_ary_push(definitions, noko_xml_namespace_wrap(c_namespace, c_node->doc));
    c_namespace = c_namespace->next;
  }

  return definitions;
}
```
   Returns   Namespaces that are defined directly on this node, as an Array of [`Namespace`](namespace) objects. The array will be empty if no namespaces are defined on this node.

   **Example:**

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns="http://example.com/root">
    <first/>
    <second xmlns="http://example.com/child" xmlns:unused="http://example.com/unused"/>
    <foo:third xmlns:foo="http://example.com/foo"/>
  </root>
EOF
doc.at_xpath("//root:first", "root" => "http://example.com/root").namespace_definitions
# => []
doc.at_xpath("//xmlns:second", "xmlns" => "http://example.com/child").namespace_definitions
# => [#(Namespace:0x3c { href = "http://example.com/child" }),
#     #(Namespace:0x50 {
#       prefix = "unused",
#       href = "http://example.com/unused"
#       })]
doc.at_xpath("//foo:third", "foo" => "http://example.com/foo").namespace_definitions
# => [#(Namespace:0x64 { prefix = "foo", href = "http://example.com/foo" })]

```
       namespace\_scopes() → Array<Nokogiri::XML::Namespace>  Show source   
 
```
static VALUE
rb_xml_node_namespace_scopes(VALUE rb_node)
{
  xmlNodePtr c_node ;
  xmlNsPtr *namespaces;
  VALUE scopes = rb_ary_new();
  int j;

  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  namespaces = xmlGetNsList(c_node->doc, c_node);
  if (!namespaces) {
    return scopes;
  }

  for (j = 0 ; namespaces[j] != NULL ; ++j) {
    rb_ary_push(scopes, noko_xml_namespace_wrap(namespaces[j], c_node->doc));
  }

  xmlFree(namespaces);
  return scopes;
}
```
   Returns   Array of all the Namespaces on this node and its ancestors.

   See also [`#namespaces`](node#method-i-namespaces)

 **Example:**

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns="http://example.com/root" xmlns:bar="http://example.com/bar">
    <first/>
    <second xmlns="http://example.com/child"/>
    <third xmlns:foo="http://example.com/foo"/>
  </root>
EOF
doc.at_xpath("//root:first", "root" => "http://example.com/root").namespace_scopes
# => [#(Namespace:0x3c { href = "http://example.com/root" }),
#     #(Namespace:0x50 { prefix = "bar", href = "http://example.com/bar" })]
doc.at_xpath("//child:second", "child" => "http://example.com/child").namespace_scopes
# => [#(Namespace:0x64 { href = "http://example.com/child" }),
#     #(Namespace:0x50 { prefix = "bar", href = "http://example.com/bar" })]
doc.at_xpath("//root:third", "root" => "http://example.com/root").namespace_scopes
# => [#(Namespace:0x78 { prefix = "foo", href = "http://example.com/foo" }),
#     #(Namespace:0x3c { href = "http://example.com/root" }),
#     #(Namespace:0x50 { prefix = "bar", href = "http://example.com/bar" })]

```
       namespaced\_key?(attribute, namespace)  Show source   
 
```
static VALUE
namespaced_key_eh(VALUE self, VALUE attribute, VALUE namespace)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  if (xmlHasNsProp(node, (xmlChar *)StringValueCStr(attribute),
                   NIL_P(namespace) ? NULL : (xmlChar *)StringValueCStr(namespace))) {
    return Qtrue;
  }
  return Qfalse;
}
```
  Returns true if `attribute` is set with `namespace`

       namespaces() → Hash<String(Namespace#prefix) ⇒ String(Namespace#href)>  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1116
def namespaces
  namespace_scopes.each_with_object({}) do |ns, hash|
    prefix = ns.prefix
    key = prefix ? "xmlns:#{prefix}" : "xmlns"
    hash[key] = ns.href
  end
end
```
  Fetch all the namespaces on this node and its ancestors.

 Note that the keys in this hash [`XML`](../xml) attributes that would be used to define this namespace, such as “xmlns:prefix”, not just the prefix.

 The default namespace for this node will be included with key “xmlns”.

 See also [`#namespace_scopes`](node#method-i-namespace_scopes)

  Returns   Hash containing all the namespaces on this node and its ancestors. The hash keys are the namespace prefix, and the hash value for each key is the namespace URI.

   **Example:**

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns="http://example.com/root" xmlns:in_scope="http://example.com/in_scope">
    <first/>
    <second xmlns="http://example.com/child"/>
    <third xmlns:foo="http://example.com/foo"/>
  </root>
EOF
doc.at_xpath("//root:first", "root" => "http://example.com/root").namespaces
# => {"xmlns"=>"http://example.com/root",
#     "xmlns:in_scope"=>"http://example.com/in_scope"}
doc.at_xpath("//child:second", "child" => "http://example.com/child").namespaces
# => {"xmlns"=>"http://example.com/child",
#     "xmlns:in_scope"=>"http://example.com/in_scope"}
doc.at_xpath("//root:third", "root" => "http://example.com/root").namespaces
# => {"xmlns:foo"=>"http://example.com/foo",
#     "xmlns"=>"http://example.com/root",
#     "xmlns:in_scope"=>"http://example.com/in_scope"}

```
       content=  Show source   
 
```
static VALUE
set_native_content(VALUE self, VALUE content)
{
  xmlNodePtr node, child, next ;
  Noko_Node_Get_Struct(self, xmlNode, node);

  child = node->children;
  while (NULL != child) {
    next = child->next ;
    xmlUnlinkNode(child) ;
    noko_xml_document_pin_node(child);
    child = next ;
  }

  xmlNodeSetContent(node, (xmlChar *)StringValueCStr(content));
  return content;
}
```
  Set the content for this [`Node`](node)

       next\_element  Show source   
 
```
static VALUE
next_element(VALUE self)
{
  xmlNodePtr node, sibling;
  Noko_Node_Get_Struct(self, xmlNode, node);

  sibling = xmlNextElementSibling(node);
  if (!sibling) { return Qnil; }

  return noko_xml_node_wrap(Qnil, sibling);
}
```
  Returns the next [`Nokogiri::XML::Element`](element) type sibling node.

       next\_sibling  Show source   
 
```
static VALUE
next_sibling(VALUE self)
{
  xmlNodePtr node, sibling;
  Noko_Node_Get_Struct(self, xmlNode, node);

  sibling = node->next;
  if (!sibling) { return Qnil; }

  return noko_xml_node_wrap(Qnil, sibling) ;
}
```
  Returns the next sibling node

   Also aliased as: [next](node#method-i-next)       name  Show source   
 
```
static VALUE
get_name(VALUE self)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  if (node->name) {
    return NOKOGIRI_STR_NEW2(node->name);
  }
  return Qnil;
}
```
  Returns the name for this [`Node`](node)

   Also aliased as: [name](node#method-i-name)      node\_name=(new\_name) Show source   
 
```
static VALUE
set_name(VALUE self, VALUE new_name)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  xmlNodeSetName(node, (xmlChar *)StringValueCStr(new_name));
  return new_name;
}
```
  Set the name for this [`Node`](node)

   Also aliased as: [name=](node#method-i-name-3D)       node\_type  Show source   
 
```
static VALUE
node_type(VALUE self)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  return INT2NUM(node->type);
}
```
  Get the type for this [`Node`](node)

   Also aliased as: [type](node#method-i-type)       parent  Show source   
 
```
static VALUE
get_parent(VALUE self)
{
  xmlNodePtr node, parent;
  Noko_Node_Get_Struct(self, xmlNode, node);

  parent = node->parent;
  if (!parent) { return Qnil; }

  return noko_xml_node_wrap(Qnil, parent) ;
}
```
  Get the parent [`Node`](node) for this [`Node`](node)

      parse(string\_or\_io, options = nil) { |options| ... } Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1030
def parse(string_or_io, options = nil)
  ##
  # When the current node is unparented and not an element node, use the
  # document as the parsing context instead. Otherwise, the in-context
  # parser cannot find an element or a document node.
  # Document Fragments are also not usable by the in-context parser.
  if !element? && !document? && (!parent || parent.fragment?)
    return document.parse(string_or_io, options)
  end

  options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)
  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  contents = if string_or_io.respond_to?(:read)
    string_or_io.read
  else
    string_or_io
  end

  return Nokogiri::XML::NodeSet.new(document) if contents.empty?

  # libxml2 does not obey the +recover+ option after encountering errors during +in_context+
  # parsing, and so this horrible hack is here to try to emulate recovery behavior.
  #
  # Unfortunately, this means we're no longer parsing "in context" and so namespaces that
  # would have been inherited from the context node won't be handled correctly. This hack was
  # written in 2010, and I regret it, because it's silently degrading functionality in a way
  # that's not easily prevented (or even detected).
  #
  # I think preferable behavior would be to either:
  #
  # a. add an error noting that we "fell back" and pointing the user to turning off the +recover+ option
  # b. don't recover, but raise a sensible exception
  #
  # For context and background: https://github.com/sparklemotion/nokogiri/issues/313
  # FIXME bug report: https://github.com/sparklemotion/nokogiri/issues/2092
  error_count = document.errors.length
  node_set = in_context(contents, options.to_i)
  if node_set.empty? && (document.errors.length > error_count)
    if options.recover?
      fragment = document.related_class("DocumentFragment").parse(contents)
      node_set = fragment.children
    else
      raise document.errors[error_count]
    end
  end
  node_set
end
```
  Parse `string_or_io` as a document fragment within the context of **this** node. Returns a [`XML::NodeSet`](nodeset) containing the nodes parsed from `string_or_io`.

       path  Show source   
 
```
static VALUE
rb_xml_node_path(VALUE rb_node)
{
  xmlNodePtr c_node;
  xmlChar *c_path ;
  VALUE rval;

  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  c_path = xmlGetNodePath(c_node);
  if (c_path == NULL) {
    // see https://github.com/sparklemotion/nokogiri/issues/2250
    // this behavior is clearly undesirable, but is what libxml <= 2.9.10 returned, and so we
    // do this for now to preserve the behavior across libxml2 versions.
    rval = NOKOGIRI_STR_NEW2("?");
  } else {
    rval = NOKOGIRI_STR_NEW2(c_path);
    xmlFree(c_path);
  }

  return rval ;
}
```
  Returns the path associated with this [`Node`](node)

       pointer\_id() → Integer  Show source   
 
```
static VALUE
rb_xml_node_pointer_id(VALUE self)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);

  return rb_uint2inum((uintptr_t)(node));
}
```
   Returns   A unique id for this node based on the internal memory structures. This method is used by [`#==`](node#method-i-3D-3D) to determine node identity.

         previous\_element  Show source   
 
```
static VALUE
previous_element(VALUE self)
{
  xmlNodePtr node, sibling;
  Noko_Node_Get_Struct(self, xmlNode, node);

  /*
   *  note that we don't use xmlPreviousElementSibling here because it's buggy pre-2.7.7.
   */
  sibling = node->prev;
  if (!sibling) { return Qnil; }

  while (sibling && sibling->type != XML_ELEMENT_NODE) {
    sibling = sibling->prev;
  }

  return sibling ? noko_xml_node_wrap(Qnil, sibling) : Qnil ;
}
```
  Returns the previous [`Nokogiri::XML::Element`](element) type sibling node.

       previous\_sibling  Show source   
 
```
static VALUE
previous_sibling(VALUE self)
{
  xmlNodePtr node, sibling;
  Noko_Node_Get_Struct(self, xmlNode, node);

  sibling = node->prev;
  if (!sibling) { return Qnil; }

  return noko_xml_node_wrap(Qnil, sibling);
}
```
  Returns the previous sibling node

   Also aliased as: [previous](node#method-i-previous)      processing\_instruction?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1150
def processing_instruction?
  type == PI_NODE
end
```
  Returns true if this is a [`ProcessingInstruction`](processinginstruction) node

      read\_only?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1175
def read_only?
  # According to gdome2, these are read-only node types
  [NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type)
end
```
  Is this a read only node?

       related\_class(class\_name) → Class  Show source   
 
```
# File lib/nokogiri/class_resolver.rb, line 46
def related_class(class_name)
  klass = nil
  inspecting = self.class

  while inspecting
    namespace_path = inspecting.name.split("::")[0..-2]
    inspecting = inspecting.superclass

    next unless VALID_NAMESPACES.include?(namespace_path.last)

    related_class_name = (namespace_path << class_name).join("::")
    klass = begin
      Object.const_get(related_class_name)
    rescue NameError
      nil
    end
    break if klass
  end
  klass
end
```
   Included from [Nokogiri::ClassResolver](../classresolver)  Find a class constant within the

 Some examples:

 
```
Nokogiri::XML::Document.new.related_class("DocumentFragment")
# => Nokogiri::XML::DocumentFragment
Nokogiri::HTML4::Document.new.related_class("DocumentFragment")
# => Nokogiri::HTML4::DocumentFragment

```
 Note this will also work for subclasses that follow the same convention, e.g.:

 
```
Loofah::HTML::Document.new.related_class("DocumentFragment")
# => Loofah::HTML::DocumentFragment

```
 And even if it’s a subclass, this will iterate through the superclasses:

 
```
class ThisIsATopLevelClass < Nokogiri::HTML4::Builder ; end
ThisIsATopLevelClass.new.related_class("Document")
# => Nokogiri::HTML4::Document

```
       text() → String     Alias for: [content](node#method-i-content)      text?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1155
def text?
  type == TEXT_NODE
end
```
  Returns true if this is a [`Text`](text) node

      to\_s() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1190
def to_s
  document.xml? ? to_xml : to_html
end
```
  Turn this node in to a string. If the document is [`HTML`](../html4), this method returns html. If the document is [`XML`](../xml), this method returns [`XML`](../xml).

       to\_str() → String     Alias for: [content](node#method-i-content)      traverse() { |self| ... } Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1233
def traverse(&block)
  children.each { |j| j.traverse(&block) }
  yield(self)
end
```
  Yields self and all children to `block` recursively.

       node\_type     Alias for: [node\_type](node#method-i-node_type)       unlink() → self  Show source   
 
```
static VALUE
unlink_node(VALUE self)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  xmlUnlinkNode(node);
  noko_xml_document_pin_node(node);
  return self;
}
```
  Unlink this node from its current context.

   Also aliased as: [remove](node#method-i-remove)      xml?() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1135
def xml?
  type == DOCUMENT_NODE
end
```
  Returns true if this is an [`XML::Document`](document) node

      ### Protected Instance Methods

     coerce(data) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1473
      def coerce(data)
        case data
        when XML::NodeSet
          return data
        when XML::DocumentFragment
          return data.children
        when String
          return fragment(data).children
        when Document, XML::Attr
          # unacceptable
        when XML::Node
          return data
        end

        raise ArgumentError, <<~EOERR
          Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
          (You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)
        EOERR
      end
```
         Manipulating Document Structure
--------------------------------

  [↑ top](#top)     ### Public Instance Methods

     <<(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 256
def <<(node_or_tags)
  add_child(node_or_tags)
  self
end
```
  Add `node_or_tags` as a child of this [`Node`](node).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns `self`, to support chaining of calls (e.g., root << child1 << child2)

 Also see related method `add_child`.

      add\_child(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 148
def add_child(node_or_tags)
  node_or_tags = coerce(node_or_tags)
  if node_or_tags.is_a?(XML::NodeSet)
    node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) }
  else
    add_child_node_and_reparent_attrs(node_or_tags)
  end
  node_or_tags
end
```
  Add `node_or_tags` as a child of this [`Node`](node).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String).

 Also see related method +<<+.

       add\_namespace(prefix, href) → Nokogiri::XML::Namespace     Alias for: [add\_namespace\_definition](node#method-i-add_namespace_definition)       add\_namespace\_definition(prefix, href) → Nokogiri::XML::Namespace  Show source   
 
```
static VALUE
rb_xml_node_add_namespace_definition(VALUE rb_node, VALUE rb_prefix, VALUE rb_href)
{
  xmlNodePtr c_node, element;
  xmlNsPtr c_namespace;
  const xmlChar *c_prefix = (const xmlChar *)(NIL_P(rb_prefix) ? NULL : StringValueCStr(rb_prefix));

  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);
  element = c_node ;

  c_namespace = xmlSearchNs(c_node->doc, c_node, c_prefix);

  if (!c_namespace) {
    if (c_node->type != XML_ELEMENT_NODE) {
      element = c_node->parent;
    }
    c_namespace = xmlNewNs(element, (const xmlChar *)StringValueCStr(rb_href), c_prefix);
  }

  if (!c_namespace) {
    return Qnil ;
  }

  if (NIL_P(rb_prefix) || c_node != element) {
    xmlSetNs(c_node, c_namespace);
  }

  return noko_xml_namespace_wrap(c_namespace, c_node->doc);
}
```
  Adds a namespace definition to this node with `prefix` using `href` value, as if this node had included an attribute “xmlns:prefix=href”.

 A default namespace definition for this node can be added by passing `nil` for `prefix`.

  Parameters   * `prefix` (String, `nil`) An [XML Name](https://www.w3.org/TR/xml-names/#ns-decl)
* `href` (String) The [URI reference](https://www.w3.org/TR/xml-names/#sec-namespaces)

  Returns   The new [`Nokogiri::XML::Namespace`](namespace)

   **Example:** adding a non-default namespace definition

 
```
doc = Nokogiri::XML("<store><inventory></inventory></store>")
inventory = doc.at_css("inventory")
inventory.add_namespace_definition("automobile", "http://alices-autos.com/")
inventory.add_namespace_definition("bicycle", "http://bobs-bikes.com/")
inventory.add_child("<automobile:tire>Michelin model XGV, size 75R</automobile:tire>")
doc.to_xml
# => "<?xml version=\"1.0\"?>\n" +
#    "<store>\n" +
#    "  <inventory xmlns:automobile=\"http://alices-autos.com/\" xmlns:bicycle=\"http://bobs-bikes.com/\">\n" +
#    "    <automobile:tire>Michelin model XGV, size 75R</automobile:tire>\n" +
#    "  </inventory>\n" +
#    "</store>\n"

```
 **Example:** adding a default namespace definition

 
```
doc = Nokogiri::XML("<store><inventory><tire>Michelin model XGV, size 75R</tire></inventory></store>")
doc.at_css("tire").add_namespace_definition(nil, "http://bobs-bikes.com/")
doc.to_xml
# => "<?xml version=\"1.0\"?>\n" +
#    "<store>\n" +
#    "  <inventory>\n" +
#    "    <tire xmlns=\"http://bobs-bikes.com/\">Michelin model XGV, size 75R</tire>\n" +
#    "  </inventory>\n" +
#    "</store>\n"

```
   Also aliased as: [add\_namespace](node#method-i-add_namespace)      add\_next\_sibling(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 288
def add_next_sibling(node_or_tags)
  raise ArgumentError,
    "A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)

  add_sibling(:next, node_or_tags)
end
```
  Insert `node_or_tags` after this [`Node`](node) (as a sibling).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String).

 Also see related method `after`.

   Also aliased as: [next=](node#method-i-next-3D)      add\_previous\_sibling(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 271
def add_previous_sibling(node_or_tags)
  raise ArgumentError,
    "A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)

  add_sibling(:previous, node_or_tags)
end
```
  Insert `node_or_tags` before this [`Node`](node) (as a sibling).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String).

 Also see related method `before`.

   Also aliased as: [previous=](node#method-i-previous-3D)      after(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 318
def after(node_or_tags)
  add_next_sibling(node_or_tags)
  self
end
```
  Insert `node_or_tags` after this node (as a sibling).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a [`Nokogiri::XML::DocumentFragment`](documentfragment), or a String containing markup.

 Returns `self`, to support chaining of calls.

 Also see related method `add_next_sibling`.

      before(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 304
def before(node_or_tags)
  add_previous_sibling(node_or_tags)
  self
end
```
  Insert `node_or_tags` before this node (as a sibling).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns `self`, to support chaining of calls.

 Also see related method `add_previous_sibling`.

      children=(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 349
def children=(node_or_tags)
  node_or_tags = coerce(node_or_tags)
  children.unlink
  if node_or_tags.is_a?(XML::NodeSet)
    node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) }
  else
    add_child_node_and_reparent_attrs(node_or_tags)
  end
end
```
  Set the content for this [`Node`](node) `node_or_tags`

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a [`Nokogiri::XML::DocumentFragment`](documentfragment), or a String containing markup.

 Also see related method `inner_html=`

      content=(string) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 411
def content=(string)
  self.native_content = encode_special_chars(string.to_s)
end
```
  Set the Node’s content to a [`Text`](text) node containing `string`. The string gets [`XML`](../xml) escaped, not interpreted as markup.

      default\_namespace=(url) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 427
def default_namespace=(url)
  add_namespace_definition(nil, url)
end
```
  Adds a default namespace supplied as a string `url` href, to self. The consequence is as an xmlns attribute with supplied argument were present in parsed [`XML`](../xml). A default namespace set with this method will now show up in [`#attributes`](node#method-i-attributes), but when this node is serialized to [`XML`](../xml) an “xmlns” attribute will appear. See also [`#namespace`](node#method-i-namespace) and [`#namespace=`](node#method-i-namespace-3D)

      do\_xinclude(options = XML::ParseOptions::DEFAULT\_XML) { |options| ... } Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 454
def do_xinclude(options = XML::ParseOptions::DEFAULT_XML)
  options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
  yield options if block_given?

  # call c extension
  process_xincludes(options.to_i)
end
```
  Do xinclude substitution on the subtree below node. If given a block, a [`Nokogiri::XML::ParseOptions`](parseoptions) object initialized from `options`, will be passed to it, allowing more convenient modification of the parser options.

      inner\_html=(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 338
def inner_html=(node_or_tags)
  self.children = node_or_tags
end
```
  Set the content for this [`Node`](node) to `node_or_tags`.

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a [`Nokogiri::XML::DocumentFragment`](documentfragment), or a String containing markup.

 ⚠ Please note that despite the name, this method will **not** always parse a String argument as [`HTML`](../html4). A String argument will be parsed with the `DocumentFragment` parser related to this node’s document.

 For example, if the document is an [`HTML4::Document`](../html4/document) then the string will be parsed as [`HTML4`](../html4) using [`HTML4::DocumentFragment`](../html4/documentfragment); but if the document is an [`XML::Document`](document) then it will parse the string as [`XML`](../xml) using [`XML::DocumentFragment`](documentfragment).

 Also see related method `children=`

       name=(new\_name)     Alias for: [node\_name=](node#method-i-node_name-3D)      namespace=(ns) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 437
def namespace=(ns)
  return set_namespace(ns) unless ns

  unless Nokogiri::XML::Namespace === ns
    raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
  end
  if ns.document != document
    raise ArgumentError, "namespace must be declared on the same document"
  end

  set_namespace(ns)
end
```
  Set the default namespace on this node (as would be defined with an “xmlns=” attribute in [`XML`](../xml) source), as a [`Namespace`](namespace) object `ns`. Note that a [`Namespace`](namespace) added this way will NOT be serialized as an xmlns attribute for this node. You probably want [`#default_namespace=`](node#method-i-default_namespace-3D) instead, or perhaps [`#add_namespace_definition`](node#method-i-add_namespace_definition) with a nil prefix argument.

       next\_sibling     Alias for: [next\_sibling](node#method-i-next_sibling)      next=(node\_or\_tags)    Alias for: [add\_next\_sibling](node#method-i-add_next_sibling)      parent=(parent\_node) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 417
def parent=(parent_node)
  parent_node.add_child(self)
end
```
  Set the parent [`Node`](node) for this [`Node`](node)

      prepend\_child(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 168
def prepend_child(node_or_tags)
  if (first = children.first)
    # Mimic the error add_child would raise.
    raise "Document already has a root node" if document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)

    first.__send__(:add_sibling, :previous, node_or_tags)
  else
    add_child(node_or_tags)
  end
end
```
  Add `node_or_tags` as the first child of this [`Node`](node).

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String).

 Also see related method `add_child`.

       previous\_sibling     Alias for: [previous\_sibling](node#method-i-previous_sibling)      previous=(node\_or\_tags)    Alias for: [add\_previous\_sibling](node#method-i-add_previous_sibling)      remove()    Alias for: [unlink](node#method-i-unlink)      replace(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 369
def replace(node_or_tags)
  raise("Cannot replace a node with no parent") unless parent

  # We cannot replace a text node directly, otherwise libxml will return
  # an internal error at parser.c:13031, I don't know exactly why
  # libxml is trying to find a parent node that is an element or document
  # so I can't tell if this is bug in libxml or not. issue #775.
  if text?
    replacee = Nokogiri::XML::Node.new("dummy", document)
    add_previous_sibling_node(replacee)
    unlink
    return replacee.replace(node_or_tags)
  end

  node_or_tags = parent.coerce(node_or_tags)

  if node_or_tags.is_a?(XML::NodeSet)
    node_or_tags.each { |n| add_previous_sibling(n) }
    unlink
  else
    replace_node(node_or_tags)
  end
  node_or_tags
end
```
  Replace this [`Node`](node) with `node_or_tags`.

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup.

 Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String).

 Also see related method `swap`.

      swap(node\_or\_tags) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 403
def swap(node_or_tags)
  replace(node_or_tags)
  self
end
```
  Swap this [`Node`](node) for `node_or_tags`

 `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String Containing markup.

 Returns self, to support chaining of calls.

 Also see related method `replace`.

       wrap(markup) → self  Show source    wrap(node) → self    
 
```
# File lib/nokogiri/xml/node.rb, line 223
def wrap(node_or_tags)
  case node_or_tags
  when String
    context_node = parent || document
    new_parent = context_node.coerce(node_or_tags).first
    if new_parent.nil?
      raise "Failed to parse '#{node_or_tags}' in the context of a '#{context_node.name}' element"
    end
  when XML::Node
    new_parent = node_or_tags.dup
  else
    raise ArgumentError, "Requires a String or Node argument, and cannot accept a #{node_or_tags.class}"
  end

  if parent
    add_next_sibling(new_parent)
  else
    new_parent.unlink
  end
  new_parent.add_child(self)

  self
end
```
  Wrap this [`Node`](node) with the node parsed from `markup` or a dup of the `node`.

  Parameters   * **markup** (String) Markup that is parsed and used as the wrapper. This node’s parent, if it exists, is used as the context node for parsing; otherwise the associated document is used. If the parsed fragment has multiple roots, the first root node is used as the wrapper.
* **node** ([`Nokogiri::XML::Node`](node)) An element that is ‘#dup`ed and used as the wrapper.

  Returns   `self`, to support chaining.

   Also see [`NodeSet#wrap`](nodeset#method-i-wrap)

 **Example** with a `String` argument:

 
```
doc = Nokogiri::HTML5(<<~HTML)
  <html><body>
    <a>asdf</a>
  </body></html>
HTML
doc.at_css("a").wrap("<div></div>")
doc.to_html
# => <html><head></head><body>
#      <div><a>asdf</a></div>
#    </body></html>

```
 **Example** with a `Node` argument:

 
```
doc = Nokogiri::HTML5(<<~HTML)
  <html><body>
    <a>asdf</a>
  </body></html>
HTML
doc.at_css("a").wrap(doc.create_element("div"))
doc.to_html
# <html><head></head><body>
#   <div><a>asdf</a></div>
# </body></html>

```
        Searching via XPath or CSS Queries
-----------------------------------

  [↑ top](#top)     ### Public Instance Methods

     %(\*args)     Included from [Nokogiri::XML::Searchable](searchable)    Alias for: [at](searchable#method-i-at)      /(\*args)     Included from [Nokogiri::XML::Searchable](searchable)    Alias for: [search](searchable#method-i-search)       >(selector) → NodeSet  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 196
def >(selector) # rubocop:disable Naming/BinaryOperatorParameterName
  ns = (document.root&.namespaces || {})
  xpath(CSS.xpath_for(selector, prefix: "./", ns: ns).first)
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this node’s immediate children using [`CSS`](../css) selector `selector`

       at(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 71
def at(*args)
  search(*args).first
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this object for `paths`, and return only the first result. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries.

 See [`Searchable#search`](searchable#method-i-search) for more information.

   Also aliased as: [%](searchable#method-i-25)       at\_css(\*rules, [namespace-bindings, custom-pseudo-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 140
def at_css(*args)
  css(*args).first
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this object for [`CSS`](../css) `rules`, and return only the first match. `rules` must be one or more [`CSS`](../css) selectors.

 See [`Searchable#css`](searchable#method-i-css) for more information.

       at\_xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 188
def at_xpath(*args)
  xpath(*args).first
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this node for [`XPath`](xpath) `paths`, and return only the first match. `paths` must be one or more [`XPath`](xpath) queries.

 See [`Searchable#xpath`](searchable#method-i-xpath) for more information.

       css(\*rules, [namespace-bindings, custom-pseudo-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 126
def css(*args)
  rules, handler, ns, _ = extract_params(args)

  css_internal(self, rules, handler, ns)
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this object for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example:

 
```
node.css('title')
node.css('body h1.bold')
node.css('div + p.green', 'div#one')

```
 A hash of namespace bindings may be appended. For example:

 
```
node.css('bike|tire', {'bike' => 'http://schwinn.com/'})

```
 💡 Custom [`CSS`](../css) pseudo classes may also be defined which are mapped to a custom [`XPath`](xpath) function. To define custom pseudo classes, create a class and implement the custom pseudo class you want defined. The first argument to the method will be the matching context [`NodeSet`](nodeset). Any other arguments are ones that you pass in. For example:

 
```
handler = Class.new {
  def regex(node_set, regex)
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.css('title:regex("\w+")', handler)

```
 💡 Some [`XPath`](xpath) syntax is supported in [`CSS`](../css) queries. For example, to query for an attribute:

 
```
node.css('img > @href') # returns all +href+ attributes on an +img+ element
node.css('img / @href') # same

# ⚠ this returns +class+ attributes from all +div+ elements AND THEIR CHILDREN!
node.css('div @class')

node.css

```
 💡 Array-like syntax is supported in [`CSS`](../css) queries as an alternative to using +:nth-child()+.

 ⚠ NOTE that indices are 1-based like `:nth-child` and not 0-based like Ruby Arrays. For example:

 
```
# equivalent to 'li:nth-child(2)'
node.css('li[2]') # retrieve the second li element in a list

```
 ⚠ NOTE that the [`CSS`](../css) query string is case-sensitive with regards to your document type. [`HTML`](../html4) tags will match only lowercase [`CSS`](../css) queries, so if you search for “H1” in an [`HTML`](../html4) document, you’ll never find anything. However, “H1” might be found in an [`XML`](../xml) document, where tags names are case-sensitive (e.g., “H1” is distinct from “h1”).

       search(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 51
def search(*args)
  paths, handler, ns, binds = extract_params(args)

  xpaths = paths.map(&:to_s).map do |path|
    LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns)
  end.flatten.uniq

  xpath(*(xpaths + [ns, handler, binds].compact))
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this object for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries:

 
```
node.search("div.employee", ".//title")

```
 A hash of namespace bindings may be appended:

 
```
node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'})
node.search('bike|tire', {'bike' => 'http://schwinn.com/'})

```
 For [`XPath`](xpath) queries, a hash of variable bindings may also be appended to the namespace bindings. For example:

 
```
node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'})

```
 💡 Custom [`XPath`](xpath) functions and [`CSS`](../css) pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

 
```
handler = Class.new {
  def regex node_set, regex
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler)

```
 See [`Searchable#xpath`](searchable#method-i-xpath) and [`Searchable#css`](searchable#method-i-css) for further usage help.

   Also aliased as: [/](searchable#method-i-2F)       xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 174
def xpath(*args)
  paths, handler, ns, binds = extract_params(args)

  xpath_internal(self, paths, handler, ns, binds)
end
```
   Included from [Nokogiri::XML::Searchable](searchable)  Search this node for [`XPath`](xpath) `paths`. `paths` must be one or more [`XPath`](xpath) queries.

 
```
node.xpath('.//title')

```
 A hash of namespace bindings may be appended. For example:

 
```
node.xpath('.//foo:name', {'foo' => 'http://example.org/'})
node.xpath('.//xmlns:name', node.root.namespaces)

```
 A hash of variable bindings may also be appended to the namespace bindings. For example:

 
```
node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'})

```
 💡 Custom [`XPath`](xpath) functions may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

 
```
handler = Class.new {
  def regex(node_set, regex)
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.xpath('.//title[regex(., "\w+")]', handler)

```
        Serialization and Generating Output
------------------------------------

  [↑ top](#top)     ### Public Instance Methods

     canonicalize(mode = XML::XML\_C14N\_1\_0, inclusive\_namespaces = nil, with\_comments = false) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1398
def canonicalize(mode = XML::XML_C14N_1_0, inclusive_namespaces = nil, with_comments = false)
  c14n_root = self
  document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent|
    tn = node.is_a?(XML::Node) ? node : parent
    tn == c14n_root || tn.ancestors.include?(c14n_root)
  end
end
```
        deconstruct\_keys(array\_of\_names) → Hash  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1459
def deconstruct_keys(keys)
  requested_keys = DECONSTRUCT_KEYS & keys
  {}.tap do |values|
    requested_keys.each do |key|
      method = DECONSTRUCT_METHODS[key] || key
      values[key] = send(method)
    end
  end
end
```
  Returns a hash describing the [`Node`](node), to use in pattern matching.

 Valid keys and their values:

 * `name` → (String) The name of this node, or “text” if it is a [`Text`](text) node.
* `namespace` → ([`Namespace`](namespace), nil) The namespace of this node, or nil if there is no namespace.
* `attributes` → (Array<Attr>) The attributes of this node.
* `children` → (Array<Node>) The children of this node. 💡 Note this includes text nodes.
* `elements` → (Array<Node>) The child elements of this node. 💡 Note this does not include text nodes.
* `content` → (String) The contents of all the text nodes in this node’s subtree. See [`#content`](node#method-i-content).
* `inner_html` → (String) The inner markup for the children of this node. See [`#inner_html`](node#method-i-inner_html).

 ⚡ This is an experimental feature, available since v1.14.0

 **Example**

 
```
doc = Nokogiri::XML.parse(<<~XML)
  <?xml version="1.0"?>
  <parent xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko">
    <child1 foo="abc" noko:bar="def">First</child1>
    <noko:child2 foo="qwe" noko:bar="rty">Second</noko:child2>
  </parent>
XML

doc.root.deconstruct_keys([:name, :namespace])
# => {:name=>"parent",
#     :namespace=>
#      #(Namespace:0x35c { href = "http://nokogiri.org/ns/default" })}

doc.root.deconstruct_keys([:inner_html, :content])
# => {:content=>"\n" + "  First\n" + "  Second\n",
#     :inner_html=>
#      "\n" +
#      "  <child1 foo=\"abc\" noko:bar=\"def\">First</child1>\n" +
#      "  <noko:child2 foo=\"qwe\" noko:bar=\"rty\">Second</noko:child2>\n"}

doc.root.elements.first.deconstruct_keys([:attributes])
# => {:attributes=>
#      [#(Attr:0x370 { name = "foo", value = "abc" }),
#       #(Attr:0x384 {
#         name = "bar",
#         namespace = #(Namespace:0x398 {
#           prefix = "noko",
#           href = "http://nokogiri.org/ns/noko"
#           }),
#         value = "def"
#         })]}

```
      serialize(\*args, &block) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1280
def serialize(*args, &block)
  options = if args.first.is_a?(Hash)
    args.shift
  else
    {
      encoding: args[0],
      save_with: args[1],
    }
  end

  options[:encoding] ||= document.encoding
  encoding = Encoding.find(options[:encoding] || "UTF-8")

  io = StringIO.new(String.new(encoding: encoding))

  write_to(io, options, &block)
  io.string
end
```
  Serialize [`Node`](node) using `options`. Save options can also be set using a block.

 See also [`Nokogiri::XML::Node::SaveOptions`](node/saveoptions) and [Serialization and Generating Output at `Node`](node#class-Nokogiri::XML::Node-label-Serialization+and+Generating+Output).

 These two statements are equivalent:

 
```
node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)

```
 or

 
```
node.serialize(:encoding => 'UTF-8') do |config|
  config.format.as_xml
end

```
      to\_html(options = {}) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1306
def to_html(options = {})
  to_format(SaveOptions::DEFAULT_HTML, options)
end
```
  Serialize this [`Node`](node) to [`HTML`](../html4)

 
```
doc.to_html

```
 See [`Node#write_to`](node#method-i-write_to) for a list of `options`. For formatted output, use [`Node#to_xhtml`](node#method-i-to_xhtml) instead.

      to\_xhtml(options = {}) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1327
def to_xhtml(options = {})
  to_format(SaveOptions::DEFAULT_XHTML, options)
end
```
  Serialize this [`Node`](node) to XHTML using `options`

 
```
doc.to_xhtml(:indent => 5, :encoding => 'UTF-8')

```
 See [`Node#write_to`](node#method-i-write_to) for a list of `options`

      to\_xml(options = {}) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1316
def to_xml(options = {})
  options[:save_with] ||= SaveOptions::DEFAULT_XML
  serialize(options)
end
```
  Serialize this [`Node`](node) to [`XML`](../xml) using `options`

 
```
doc.to_xml(:indent => 5, :encoding => 'UTF-8')

```
 See [`Node#write_to`](node#method-i-write_to) for a list of `options`

      write\_html\_to(io, options = {}) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1375
def write_html_to(io, options = {})
  write_format_to(SaveOptions::DEFAULT_HTML, io, options)
end
```
  Write [`Node`](node) as [`HTML`](../html4) to `io` with `options`

 See [`Node#write_to`](node#method-i-write_to) for a list of `options`

      write\_to(io, \*options) { |config| ... } Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1348
def write_to(io, *options)
  options = options.first.is_a?(Hash) ? options.shift : {}
  encoding = options[:encoding] || options[0]
  if Nokogiri.jruby?
    save_options = options[:save_with] || options[1]
    indent_times = options[:indent] || 0
  else
    save_options = options[:save_with] || options[1] || SaveOptions::FORMAT
    indent_times = options[:indent] || 2
  end
  indent_text = options[:indent_text] || " "

  # Any string times 0 returns an empty string. Therefore, use the same
  # string instead of generating a new empty string for every node with
  # zero indentation.
  indentation = indent_times.zero? ? "" : (indent_text * indent_times)

  config = SaveOptions.new(save_options.to_i)
  yield config if block_given?

  native_write_to(io, encoding, indentation, config.options)
end
```
  Write [`Node`](node) to `io` with `options`. `options` modify the output of this method. Valid options are:

 * `:encoding` for changing the encoding
* `:indent_text` the indentation text, defaults to one space
* `:indent` the number of `:indent_text` to use, defaults to 2
* `:save_with` a combination of [`SaveOptions`](node/saveoptions) constants.

 To save with UTF-8 indented twice:

 
```
node.write_to(io, :encoding => 'UTF-8', :indent => 2)

```
 To save indented with two dashes:

 
```
node.write_to(io, :indent_text => '-', :indent => 2)

```
      write\_xhtml\_to(io, options = {}) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1383
def write_xhtml_to(io, options = {})
  write_format_to(SaveOptions::DEFAULT_XHTML, io, options)
end
```
  Write [`Node`](node) as XHTML to `io` with `options`

 See [`Node#write_to`](node#method-i-write_to) for a list of `options`

      write\_xml\_to(io, options = {}) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 1393
def write_xml_to(io, options = {})
  options[:save_with] ||= SaveOptions::DEFAULT_XML
  write_to(io, options)
end
```
  Write [`Node`](node) as [`XML`](../xml) to `io` with `options`

 
```
doc.write_xml_to io, :encoding => 'UTF-8'

```
 See [`Node#write_to`](node#method-i-write_to) for a list of options

        Traversing Document Structure
------------------------------

  [↑ top](#top)     ### Public Instance Methods

      child() → Nokogiri::XML::Node  Show source   
 
```
static VALUE
rb_xml_node_child(VALUE self)
{
  xmlNodePtr node, child;
  Noko_Node_Get_Struct(self, xmlNode, node);

  child = node->children;
  if (!child) { return Qnil; }

  return noko_xml_node_wrap(Qnil, child);
}
```
   Returns   First of this node’s children, or `nil` if there are no children

   This is a convenience method and is equivalent to:

 
```
node.children.first

```
 See related: [`#children`](node#method-i-children)

       children() → Nokogiri::XML::NodeSet  Show source   
 
```
static VALUE
rb_xml_node_children(VALUE self)
{
  xmlNodePtr node;
  xmlNodePtr child;
  xmlNodeSetPtr set;
  VALUE document;
  VALUE node_set;

  Noko_Node_Get_Struct(self, xmlNode, node);

  child = node->children;
  set = xmlXPathNodeSetCreate(child);

  document = DOC_RUBY_OBJECT(node->doc);

  if (!child) { return noko_xml_node_set_wrap(set, document); }

  child = child->next;
  while (NULL != child) {
    xmlXPathNodeSetAddUnique(set, child);
    child = child->next;
  }

  node_set = noko_xml_node_set_wrap(set, document);

  return node_set;
}
```
   Returns   [`Nokogiri::XML::NodeSet`](nodeset) containing this node’s children.

         document() → Nokogiri::XML::Document  Show source   
 
```
static VALUE
rb_xml_node_document(VALUE self)
{
  xmlNodePtr node;
  Noko_Node_Get_Struct(self, xmlNode, node);
  return DOC_RUBY_OBJECT(node->doc);
}
```
   Returns   Parent [`Nokogiri::XML::Document`](document) for this node

          Working With Node Attributes
-----------------------------

  [↑ top](#top)     ### Public Instance Methods

      [](name) → (String, nil)  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 512
def [](name)
  get(name.to_s)
end
```
  Fetch an attribute from this node.

 ⚠ Note that attributes with namespaces cannot be accessed with this method. To access namespaced attributes, use [`#attribute_with_ns`](node#method-i-attribute_with_ns).

  Returns   (String, nil) value of the attribute `name`, or `nil` if no matching attribute exists

   **Example**

 
```
doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
child = doc.at_css("child")
child["size"] # => "large"
child["class"] # => "big wide tall"

```
 **Example:** Namespaced attributes will not be returned.

 ⚠ Note namespaced attributes may be accessed with [`#attribute`](node#method-i-attribute) or [`#attribute_with_ns`](node#method-i-attribute_with_ns)

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'>
    <child width:size='broad'/>
  </root>
EOF
doc.at_css("child")["size"] # => nil
doc.at_css("child").attribute("size").value # => "broad"
doc.at_css("child").attribute_with_ns("size", "http://example.com/widths").value
# => "broad"

```
   Also aliased as: [get\_attribute](node#method-i-get_attribute), [attr](node#method-i-attr)       []=(name, value) → value  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 550
def []=(name, value)
  set(name.to_s, value.to_s)
end
```
  Update the attribute `name` to `value`, or create the attribute if it does not exist.

 ⚠ Note that attributes with namespaces cannot be accessed with this method. To access namespaced attributes for update, use [`#attribute_with_ns`](node#method-i-attribute_with_ns). To add a namespaced attribute, see the example below.

  Returns   `value`

   **Example**

 
```
doc = Nokogiri::XML("<root><child/></root>")
child = doc.at_css("child")
child["size"] = "broad"
child.to_html
# => "<child size=\"broad\"></child>"

```
 **Example:** Add a namespaced attribute.

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'>
    <child/>
  </root>
EOF
child = doc.at_css("child")
child["size"] = "broad"
ns = doc.root.namespace_definitions.find { |ns| ns.prefix == "width" }
child.attribute("size").namespace = ns
doc.to_html
# => "<root xmlns:width=\"http://example.com/widths\">\n" +
#    "  <child width:size=\"broad\"></child>\n" +
#    "</root>\n"

```
   Also aliased as: [set\_attribute](node#method-i-set_attribute)       add\_class(names) → self  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 715
def add_class(names)
  kwattr_add("class", names)
end
```
  Ensure [`HTML`](../html4) [`CSS`](../css) classes are present on `self`. Any [`CSS`](../css) classes in `names` that already exist in the “class” attribute are *not* added. Note that any existing duplicates in the “class” attribute are not removed. Compare with [`#append_class`](node#method-i-append_class).

 This is a convenience function and is equivalent to:

 
```
node.kwattr_add("class", names)

```
 See related: [`#kwattr_add`](node#method-i-kwattr_add), [`#classes`](node#method-i-classes), [`#append_class`](node#method-i-append_class), [`#remove_class`](node#method-i-remove_class)

  Parameters   * `names` (String, Array<String>)

 [`CSS`](../css) class names to be added to the Node’s “class” attribute. May be a string containing whitespace-delimited names, or an Array of String names. Any class names already present will not be added. Any class names not present will be added. If no “class” attribute exists, one is created.

  Returns   `self` ([`Node`](node)) for ease of chaining method calls.

   **Example:** Ensure that the node has [`CSS`](../css) class “section”

 
```
node                      # => <div></div>
node.add_class("section") # => <div class="section"></div>
node.add_class("section") # => <div class="section"></div> # duplicate not added

```
 **Example:** Ensure that the node has [`CSS`](../css) classes “section” and “header”, via a String argument

 Note that the [`CSS`](../css) class “section” is not added because it is already present. Note also that the pre-existing duplicate [`CSS`](../css) class “section” is not removed.

 
```
node                             # => <div class="section section"></div>
node.add_class("section header") # => <div class="section section header"></div>

```
 **Example:** Ensure that the node has [`CSS`](../css) classes “section” and “header”, via an Array argument

 
```
node                                  # => <div></div>
node.add_class(["section", "header"]) # => <div class="section header"></div>

```
       append\_class(names) → self  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 759
def append_class(names)
  kwattr_append("class", names)
end
```
  Add [`HTML`](../html4) [`CSS`](../css) classes to `self`, regardless of duplication. Compare with [`#add_class`](node#method-i-add_class).

 This is a convenience function and is equivalent to:

 
```
node.kwattr_append("class", names)

```
 See related: [`#kwattr_append`](node#method-i-kwattr_append), [`#classes`](node#method-i-classes), [`#add_class`](node#method-i-add_class), [`#remove_class`](node#method-i-remove_class)

  Parameters   * `names` (String, Array<String>)

 [`CSS`](../css) class names to be appended to the Node’s “class” attribute. May be a string containing whitespace-delimited names, or an Array of String names. All class names passed in will be appended to the “class” attribute even if they are already present in the attribute value. If no “class” attribute exists, one is created.

  Returns   `self` ([`Node`](node)) for ease of chaining method calls.

   **Example:** Append “section” to the node’s [`CSS`](../css) “class” attribute

 
```
node                         # => <div></div>
node.append_class("section") # => <div class="section"></div>
node.append_class("section") # => <div class="section section"></div> # duplicate added!

```
 **Example:** Append “section” and “header” to the noded’s [`CSS`](../css) “class” attribute, via a String argument

 Note that the [`CSS`](../css) class “section” is appended even though it is already present

 
```
node                                # => <div class="section section"></div>
node.append_class("section header") # => <div class="section section section header"></div>

```
 **Example:** Append “section” and “header” to the node’s [`CSS`](../css) “class” attribute, via an Array argument

 
```
node                                     # => <div></div>
node.append_class(["section", "header"]) # => <div class="section header"></div>
node.append_class(["section", "header"]) # => <div class="section header section header"></div>

```
      attr(name)    Alias for: [[]](node#method-i-5B-5D)       attribute(name) → Nokogiri::XML::Attr  Show source   
 
```
static VALUE
rb_xml_node_attribute(VALUE self, VALUE name)
{
  xmlNodePtr node;
  xmlAttrPtr prop;
  Noko_Node_Get_Struct(self, xmlNode, node);
  prop = xmlHasProp(node, (xmlChar *)StringValueCStr(name));

  if (! prop) { return Qnil; }
  return noko_xml_node_wrap(Qnil, (xmlNodePtr)prop);
}
```
   Returns   Attribute ([`Nokogiri::XML::Attr`](attr)) belonging to this node with name `name`.

   ⚠ Note that attribute namespaces are ignored and only the simple (non-namespace-prefixed) name is used to find a matching attribute. In case of a simple name collision, only one of the matching attributes will be returned. In this case, you will need to use [`#attribute_with_ns`](node#method-i-attribute_with_ns).

 **Example:**

 
```
doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
child = doc.at_css("child")
child.attribute("size") # => #<Nokogiri::XML::Attr:0x550 name="size" value="large">
child.attribute("class") # => #<Nokogiri::XML::Attr:0x564 name="class" value="big wide tall">

```
 **Example** showing that namespaced attributes will not be returned:

 ⚠ Note that only one of the two matching attributes is returned.

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'
        xmlns:height='http://example.com/heights'>
    <child width:size='broad' height:size='tall'/>
  </root>
EOF
doc.at_css("child").attribute("size")
# => #(Attr:0x550 {
#      name = "size",
#      namespace = #(Namespace:0x564 {
#        prefix = "width",
#        href = "http://example.com/widths"
#        }),
#      value = "broad"
#      })

```
       attribute\_nodes() → Array<Nokogiri::XML::Attr>  Show source   
 
```
static VALUE
rb_xml_node_attribute_nodes(VALUE rb_node)
{
  xmlNodePtr c_node;

  Noko_Node_Get_Struct(rb_node, xmlNode, c_node);

  return noko_xml_node_attrs(c_node);
}
```
   Returns   Attributes (an Array of [`Nokogiri::XML::Attr`](attr)) belonging to this node.

   Note that this is the preferred alternative to [`#attributes`](node#method-i-attributes) when the simple (non-namespace-prefixed) attribute names may collide.

 **Example:**

 Contrast this with the colliding-name example from [`#attributes`](node#method-i-attributes).

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'
        xmlns:height='http://example.com/heights'>
    <child width:size='broad' height:size='tall'/>
  </root>
EOF
doc.at_css("child").attribute_nodes
# => [#(Attr:0x550 {
#       name = "size",
#       namespace = #(Namespace:0x564 {
#         prefix = "width",
#         href = "http://example.com/widths"
#         }),
#       value = "broad"
#       }),
#     #(Attr:0x578 {
#       name = "size",
#       namespace = #(Namespace:0x58c {
#         prefix = "height",
#         href = "http://example.com/heights"
#         }),
#       value = "tall"
#       })]

```
       attribute\_with\_ns(name, namespace) → Nokogiri::XML::Attr  Show source   
 
```
static VALUE
rb_xml_node_attribute_with_ns(VALUE self, VALUE name, VALUE namespace)
{
  xmlNodePtr node;
  xmlAttrPtr prop;
  Noko_Node_Get_Struct(self, xmlNode, node);
  prop = xmlHasNsProp(node, (xmlChar *)StringValueCStr(name),
                      NIL_P(namespace) ? NULL : (xmlChar *)StringValueCStr(namespace));

  if (! prop) { return Qnil; }
  return noko_xml_node_wrap(Qnil, (xmlNodePtr)prop);
}
```
   Returns   Attribute ([`Nokogiri::XML::Attr`](attr)) belonging to this node with matching `name` and `namespace`.

   * `name` (String): the simple (non-namespace-prefixed) name of the attribute
* `namespace` (String): the URI of the attribute’s namespace

 See related: [`#attribute`](node#method-i-attribute)

 **Example:**

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'
        xmlns:height='http://example.com/heights'>
    <child width:size='broad' height:size='tall'/>
  </root>
EOF
doc.at_css("child").attribute_with_ns("size", "http://example.com/widths")
# => #(Attr:0x550 {
#      name = "size",
#      namespace = #(Namespace:0x564 {
#        prefix = "width",
#        href = "http://example.com/widths"
#        }),
#      value = "broad"
#      })
doc.at_css("child").attribute_with_ns("size", "http://example.com/heights")
# => #(Attr:0x578 {
#      name = "size",
#      namespace = #(Namespace:0x58c {
#        prefix = "height",
#        href = "http://example.com/heights"
#        }),
#      value = "tall"
#      })

```
       attributes() → Hash<String ⇒ Nokogiri::XML::Attr>  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 609
def attributes
  attribute_nodes.each_with_object({}) do |node, hash|
    hash[node.node_name] = node
  end
end
```
  Fetch this node’s attributes.

 ⚠ Because the keys do not include any namespace information for the attribute, in case of a simple name collision, not all attributes will be returned. In this case, you will need to use [`#attribute_nodes`](node#method-i-attribute_nodes).

  Returns   Hash containing attributes belonging to `self`. The hash keys are String attribute names (without the namespace), and the hash values are [`Nokogiri::XML::Attr`](attr).

   **Example** with no namespaces:

 
```
doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
doc.at_css("child").attributes
# => {"size"=>#(Attr:0x550 { name = "size", value = "large" }),
#     "class"=>#(Attr:0x564 { name = "class", value = "big wide tall" })}

```
 **Example** with a namespace:

 
```
doc = Nokogiri::XML("<root xmlns:desc='http://example.com/sizes'><child desc:size='large'/></root>")
doc.at_css("child").attributes
# => {"size"=>
#      #(Attr:0x550 {
#        name = "size",
#        namespace = #(Namespace:0x564 {
#          prefix = "desc",
#          href = "http://example.com/sizes"
#          }),
#        value = "large"
#        })}

```
 **Example** with an attribute name collision:

 ⚠ Note that only one of the attributes is returned in the Hash.

 
```
doc = Nokogiri::XML(<<~EOF)
  <root xmlns:width='http://example.com/widths'
        xmlns:height='http://example.com/heights'>
    <child width:size='broad' height:size='tall'/>
  </root>
EOF
doc.at_css("child").attributes
# => {"size"=>
#      #(Attr:0x550 {
#        name = "size",
#        namespace = #(Namespace:0x564 {
#          prefix = "height",
#          href = "http://example.com/heights"
#          }),
#        value = "tall"
#        })}

```
       classes() → Array<String>  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 669
def classes
  kwattr_values("class")
end
```
  Fetch [`CSS`](../css) class names of a [`Node`](node).

 This is a convenience function and is equivalent to:

 
```
node.kwattr_values("class")

```
 See related: [`#kwattr_values`](node#method-i-kwattr_values), [`#add_class`](node#method-i-add_class), [`#append_class`](node#method-i-append_class), [`#remove_class`](node#method-i-remove_class)

  Returns   The [`CSS`](../css) classes (Array of String) present in the Node’s “class” attribute. If the attribute is empty or non-existent, the return value is an empty array.

   **Example**

 
```
node         # => <div class="section title header"></div>
node.classes # => ["section", "title", "header"]

```
      delete(name)    Alias for: [remove\_attribute](node#method-i-remove_attribute)      each() { |node\_name, value| ... } Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 635
def each
  attribute_nodes.each do |node|
    yield [node.node_name, node.value]
  end
end
```
  Iterate over each attribute name and value pair for this [`Node`](node).

      get\_attribute(name)    Alias for: [[]](node#method-i-5B-5D)      has\_attribute?(p1)    Alias for: [key?](node#method-i-key-3F)      keys() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 629
def keys
  attribute_nodes.map(&:node_name)
end
```
  Get the attribute names for this [`Node`](node).

       kwattr\_add(attribute\_name, keywords) → self  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 892
def kwattr_add(attribute_name, keywords)
  keywords = keywordify(keywords)
  current_kws = kwattr_values(attribute_name)
  new_kws = (current_kws + (keywords - current_kws)).join(" ")
  set_attribute(attribute_name, new_kws)
  self
end
```
  Ensure that values are present in a keyword attribute.

 Any values in `keywords` that already exist in the Node’s attribute values are *not* added. Note that any existing duplicates in the attribute values are not removed. Compare with [`#kwattr_append`](node#method-i-kwattr_append).

 A “keyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) “class” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the “rel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel).

 See also [`#add_class`](node#method-i-add_class), [`#kwattr_values`](node#method-i-kwattr_values), [`#kwattr_append`](node#method-i-kwattr_append), [`#kwattr_remove`](node#method-i-kwattr_remove)

  Parameters   * `attribute_name` (String) The name of the keyword attribute to be modified.
* `keywords` (String, Array<String>) Keywords to be added to the attribute named `attribute_name`. May be a string containing whitespace-delimited values, or an Array of String values. Any values already present will not be added. Any values not present will be added. If the named attribute does not exist, it is created.

  Returns   `self` ([`Nokogiri::XML::Node`](node)) for ease of chaining method calls.

   **Example:** Ensure that a `Node` has “nofollow” in its `rel` attribute.

 Note that duplicates are not added.

 
```
node                               # => <a></a>
node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a>
node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a>

```
 **Example:** Ensure that a `Node` has “nofollow” and “noreferrer” in its `rel` attribute, via a String argument.

 
```
Note that "nofollow" is not added because it is already present. Note also that the
pre-existing duplicate "nofollow" is not removed.

 node                                          # => <a rel="nofollow nofollow"></a>
 node.kwattr_add("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a>
```
 **Example:** Ensure that a `Node` has “nofollow” and “noreferrer” in its `rel` attribute, via an Array argument.

 
```
node                                               # => <a></a>
node.kwattr_add("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a>

```
 Since v1.11.0

       kwattr\_append(attribute\_name, keywords) → self  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 945
def kwattr_append(attribute_name, keywords)
  keywords = keywordify(keywords)
  current_kws = kwattr_values(attribute_name)
  new_kws = (current_kws + keywords).join(" ")
  set_attribute(attribute_name, new_kws)
  self
end
```
  Add keywords to a Node’s keyword attribute, regardless of duplication. Compare with [`#kwattr_add`](node#method-i-kwattr_add).

 A “keyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) “class” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the “rel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel).

 See also [`#append_class`](node#method-i-append_class), [`#kwattr_values`](node#method-i-kwattr_values), [`#kwattr_add`](node#method-i-kwattr_add), [`#kwattr_remove`](node#method-i-kwattr_remove)

  Parameters   * `attribute_name` (String) The name of the keyword attribute to be modified.
* `keywords` (String, Array<String>) Keywords to be added to the attribute named `attribute_name`. May be a string containing whitespace-delimited values, or an Array of String values. All values passed in will be appended to the named attribute even if they are already present in the attribute. If the named attribute does not exist, it is created.

  Returns   `self` ([`Node`](node)) for ease of chaining method calls.

   **Example:** Append “nofollow” to the `rel` attribute.

 Note that duplicates are added.

 
```
node                                  # => <a></a>
node.kwattr_append("rel", "nofollow") # => <a rel="nofollow"></a>
node.kwattr_append("rel", "nofollow") # => <a rel="nofollow nofollow"></a>

```
 **Example:** Append “nofollow” and “noreferrer” to the `rel` attribute, via a String argument.

 Note that “nofollow” is appended even though it is already present.

 
```
node                                             # => <a rel="nofollow"></a>
node.kwattr_append("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a>

```
 **Example:** Append “nofollow” and “noreferrer” to the `rel` attribute, via an Array argument.

 
```
node                                                  # => <a></a>
node.kwattr_append("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a>

```
 Since v1.11.0

       kwattr\_remove(attribute\_name, keywords) → self  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 988
def kwattr_remove(attribute_name, keywords)
  if keywords.nil?
    remove_attribute(attribute_name)
    return self
  end

  keywords = keywordify(keywords)
  current_kws = kwattr_values(attribute_name)
  new_kws = current_kws - keywords
  if new_kws.empty?
    remove_attribute(attribute_name)
  else
    set_attribute(attribute_name, new_kws.join(" "))
  end
  self
end
```
  Remove keywords from a keyword attribute. Any matching keywords that exist in the named attribute are removed, including any multiple entries.

 If no keywords remain after this operation, or if `keywords` is `nil`, the attribute is deleted from the node.

 A “keyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) “class” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the “rel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel).

 See also [`#remove_class`](node#method-i-remove_class), [`#kwattr_values`](node#method-i-kwattr_values), [`#kwattr_add`](node#method-i-kwattr_add), [`#kwattr_append`](node#method-i-kwattr_append)

  Parameters   * `attribute_name` (String) The name of the keyword attribute to be modified.
* `keywords` (String, Array<String>) Keywords to be removed from the attribute named `attribute_name`. May be a string containing whitespace-delimited values, or an Array of String values. Any keywords present in the named attribute will be removed. If no keywords remain, or if `keywords` is nil, the attribute is deleted.

  Returns   `self` ([`Node`](node)) for ease of chaining method calls.

   **Example:**

 Note that the `rel` attribute is deleted when empty.

 
```
node                                    # => <a rel="nofollow noreferrer">link</a>
node.kwattr_remove("rel", "nofollow")   # => <a rel="noreferrer">link</a>
node.kwattr_remove("rel", "noreferrer") # => <a>link</a>

```
 Since v1.11.0

       kwattr\_values(attribute\_name) → Array<String>  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 838
def kwattr_values(attribute_name)
  keywordify(get_attribute(attribute_name) || [])
end
```
  Fetch values from a keyword attribute of a [`Node`](node).

 A “keyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) “class” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the “rel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel).

 See also [`#classes`](node#method-i-classes), [`#kwattr_add`](node#method-i-kwattr_add), [`#kwattr_append`](node#method-i-kwattr_append), [`#kwattr_remove`](node#method-i-kwattr_remove)

  Parameters   * `attribute_name` (String) The name of the keyword attribute to be inspected.

  Returns   (Array<String>) The values present in the Node’s `attribute_name` attribute. If the attribute is empty or non-existent, the return value is an empty array.

   **Example:**

 
```
node                      # => <a rel="nofollow noopener external">link</a>
node.kwattr_values("rel") # => ["nofollow", "noopener", "external"]

```
 Since v1.11.0

      remove\_attribute(name) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 643
def remove_attribute(name)
  attr = attributes[name].remove if key?(name)
  clear_xpath_context if Nokogiri.jruby?
  attr
end
```
  Remove the attribute named `name`

   Also aliased as: [delete](node#method-i-delete)       remove\_class(css\_classes) → self  Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 809
def remove_class(names = nil)
  kwattr_remove("class", names)
end
```
  Remove [`HTML`](../html4) [`CSS`](../css) classes from this node. Any [`CSS`](../css) class names in `css_classes` that exist in this node’s “class” attribute are removed, including any multiple entries.

 If no [`CSS`](../css) classes remain after this operation, or if `css_classes` is `nil`, the “class” attribute is deleted from the node.

 This is a convenience function and is equivalent to:

 
```
node.kwattr_remove("class", css_classes)

```
 Also see [`#kwattr_remove`](node#method-i-kwattr_remove), [`#classes`](node#method-i-classes), [`#add_class`](node#method-i-add_class), [`#append_class`](node#method-i-append_class)

  Parameters   * `css_classes` (String, Array<String>)

 [`CSS`](../css) class names to be removed from the Node’s “class” attribute. May be a string containing whitespace-delimited names, or an Array of String names. Any class names already present will be removed. If no [`CSS`](../css) classes remain, the “class” attribute is deleted.

  Returns   `self` ([`Nokogiri::XML::Node`](node)) for ease of chaining method calls.

   **Example**: Deleting a [`CSS`](../css) class

 Note that all instances of the class “section” are removed from the “class” attribute.

 
```
node                         # => <div class="section header section"></div>
node.remove_class("section") # => <div class="header"></div>

```
 **Example**: Deleting the only remaining [`CSS`](../css) class

 Note that the attribute is removed once there are no remaining classes.

 
```
node                         # => <div class="section"></div>
node.remove_class("section") # => <div></div>

```
 **Example**: Deleting multiple [`CSS`](../css) classes

 Note that the “class” attribute is deleted once it’s empty.

 
```
node                                    # => <div class="section header float"></div>
node.remove_class(["section", "float"]) # => <div class="header"></div>

```
       []=(name, value) → value     Alias for: [[]=](node#method-i-5B-5D-3D)      value?(value) Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 623
def value?(value)
  values.include?(value)
end
```
  Does this Node’s attributes include <value>

      values() Show source   
 
```
# File lib/nokogiri/xml/node.rb, line 617
def values
  attribute_nodes.map(&:value)
end
```
  Get the attribute values for this [`Node`](node).

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Node.html>

class Nokogiri::XML::ParseOptions
==================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  Options that control the parsing behavior for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema).

 These options directly expose libxml2’s parse options, which are all boolean in the sense that an option is “on” or “off”.

 💡 Note that [`HTML5`](../html5) parsing has a separate, orthogonal set of options due to the nature of the [`HTML5`](../html5) specification. See [`Nokogiri::HTML5`](../html5).

 ⚠ Not all parse options are supported on JRuby. [`Nokogiri`](../../nokogiri) will attempt to invoke the equivalent behavior in Xerces/NekoHTML on JRuby when it’s possible.

 Setting and unsetting parse options
-----------------------------------

 You can build your own combinations of parse options by using any of the following methods:

   [`ParseOptions`](parseoptions) method chaining   Every option has an equivalent method in lowercase. You can chain these methods together to set various combinations.

 
```
# Set the HUGE & PEDANTIC options
po = Nokogiri::XML::ParseOptions.new.huge.pedantic
doc = Nokogiri::XML::Document.parse(xml, nil, nil, po)

```
 Every option has an equivalent `no{option}` method in lowercase. You can call these methods on an instance of [`ParseOptions`](parseoptions) to unset the option.

 
```
# Set the HUGE & PEDANTIC options
po = Nokogiri::XML::ParseOptions.new.huge.pedantic

# later we want to modify the options
po.nohuge # Unset the HUGE option
po.nopedantic # Unset the PEDANTIC option

```
 💡 Note that some options begin with “no” leading to the logical but perhaps unintuitive double negative:

 
```
po.nocdata # Set the NOCDATA parse option
po.nonocdata # Unset the NOCDATA parse option

```
 💡 Note that negation is not available for [`STRICT`](parseoptions#STRICT), which is itself a negation of all other features.

  Using Ruby Blocks   Most parsing methods will accept a block for configuration of parse options, and we recommend chaining the setter methods:

 
```
doc = Nokogiri::XML::Document.parse(xml) { |config| config.huge.pedantic }

```
   [`ParseOptions`](parseoptions) constants   You can also use the constants declared under [`Nokogiri::XML::ParseOptions`](parseoptions) to set various combinations. They are bits in a bitmask, and so can be combined with bitwise operators:

 
```
po = Nokogiri::XML::ParseOptions.new(Nokogiri::XML::ParseOptions::HUGE | Nokogiri::XML::ParseOptions::PEDANTIC)
doc = Nokogiri::XML::Document.parse(xml, nil, nil, po)

```
       ### Constants

   BIG\_LINES   Support line numbers up to `long int` (default is a `short int`). On by default for for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema).

  COMPACT   Compact small text nodes. Off by default.

 ⚠ No modification of the DOM tree is allowed after parsing. libxml2 may crash if you try to modify the tree.

  DEFAULT\_HTML   The options mask used by default used for parsing [`HTML4::Document`](../html4/document) and [`HTML4::DocumentFragment`](../html4/documentfragment)

  DEFAULT\_SCHEMA   The options mask used by default used for parsing [`XML::Schema`](schema)

  DEFAULT\_XML   The options mask used by default for parsing [`XML::Document`](document) and [`XML::DocumentFragment`](documentfragment)

  DEFAULT\_XSLT   The options mask used by default used for parsing [`XSLT::Stylesheet`](../xslt/stylesheet)

  DTDATTR   Default [`DTD`](dtd) attributes. On by default for [`XSLT::Stylesheet`](../xslt/stylesheet).

  DTDLOAD   Load external subsets. On by default for [`XSLT::Stylesheet`](../xslt/stylesheet).

 ⚠ **It is UNSAFE to set this option** when parsing untrusted documents.

  DTDVALID   Validate with the [`DTD`](dtd). Off by default.

  HUGE   Relax any hardcoded limit from the parser. Off by default.

 ⚠ There may be a performance penalty when this option is set.

  NOBASEFIX   Do not fixup XInclude xml:base uris. Off by default

  NOBLANKS   Remove blank nodes. Off by default.

  NOCDATA   Merge [`CDATA`](cdata) as text nodes. On by default for [`XSLT::Stylesheet`](../xslt/stylesheet).

  NODICT   Do not reuse the context dictionary. Off by default.

  NOENT   Substitute entities. Off by default.

 ⚠ This option enables entity substitution, contrary to what the name implies.

 ⚠ **It is UNSAFE to set this option** when parsing untrusted documents.

  NOERROR   Suppress error reports. On by default for [`HTML4::Document`](../html4/document) and [`HTML4::DocumentFragment`](../html4/documentfragment)

  NONET   Forbid network access. On by default for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema).

 ⚠ **It is UNSAFE to unset this option** when parsing untrusted documents.

  NOWARNING   Suppress warning reports. On by default for [`HTML4::Document`](../html4/document) and [`HTML4::DocumentFragment`](../html4/documentfragment)

  NOXINCNODE   Do not generate XInclude START/END nodes. Off by default.

  NSCLEAN   Remove redundant namespaces declarations. Off by default.

  OLD10   Parse using XML-1.0 before update 5. Off by default

  PEDANTIC   Enable pedantic error reporting. Off by default.

  RECOVER   Recover from errors. On by default for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema).

  SAX1   Use the [`SAX1`](parseoptions#SAX1) interface internally. Off by default.

  STRICT   Strict parsing

  XINCLUDE   Implement XInclude substitution. Off by default.

      ### Attributes

    options[RW]     to\_i[RW]      ### Public Class Methods

     new(options = STRICT) Show source   
 
```
# File lib/nokogiri/xml/parse_options.rb, line 165
def initialize(options = STRICT)
  @options = options
end
```
       ### Public Instance Methods

     ==(other) Show source   
 
```
# File lib/nokogiri/xml/parse_options.rb, line 198
def ==(other)
  other.to_i == to_i
end
```
       inspect() Show source   
 
```
# File lib/nokogiri/xml/parse_options.rb, line 204
def inspect
  options = []
  self.class.constants.each do |k|
    options << k.downcase if send(:"#{k.downcase}?")
  end
  super.sub(/>$/, " " + options.join(", ") + ">")
end
```
   Calls superclass method       strict() Show source   
 
```
# File lib/nokogiri/xml/parse_options.rb, line 189
def strict
  @options &= ~RECOVER
  self
end
```
       strict?() Show source   
 
```
# File lib/nokogiri/xml/parse_options.rb, line 194
def strict?
  @options & RECOVER == STRICT
end
```
     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/ParseOptions.html>

class Nokogiri::XML::ProcessingInstruction
===========================================



Parent:
cNokogiriXmlNode
  [`ProcessingInstruction`](processinginstruction) represents a [`ProcessingInstruction`](processinginstruction) node in an xml document.

     ### Public Class Methods

      new(document, name, content)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr xml_doc;
  xmlNodePtr node;
  VALUE document;
  VALUE name;
  VALUE content;
  VALUE rest;
  VALUE rb_node;

  rb_scan_args(argc, argv, "3*", &document, &name, &content, &rest);

  Data_Get_Struct(document, xmlDoc, xml_doc);

  node = xmlNewDocPI(
           xml_doc,
           (const xmlChar *)StringValueCStr(name),
           (const xmlChar *)StringValueCStr(content)
         );

  noko_xml_document_pin_node(node);

  rb_node = noko_xml_node_wrap(klass, node);
  rb_obj_call_init(rb_node, argc, argv);

  if (rb_block_given_p()) { rb_yield(rb_node); }

  return rb_node;
}
```
  Create a new [`ProcessingInstruction`](processinginstruction) element on the `document` with `name` and `content`

      new(document, name, content) Show source   
 
```
# File lib/nokogiri/xml/processing_instruction.rb, line 6
def initialize(document, name, content)
  super(document, name)
end
```
   Calls superclass method     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/ProcessingInstruction.html>

class Nokogiri::XML::Reader
============================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
Included modules:
  The [`Reader`](reader) parser allows you to effectively pull parse an [`XML`](../xml) document. Once instantiated, call [`Nokogiri::XML::Reader#each`](reader#method-i-each) to iterate over each node. Note that you may only iterate over the document once!

 [`Nokogiri::XML::Reader`](reader) parses an [`XML`](../xml) document similar to the way a cursor would move. The [`Reader`](reader) is given an [`XML`](../xml) document, and yields nodes to an each block.

 Here is an example of usage:

 
```
reader = Nokogiri::XML::Reader(<<-eoxml)
  <x xmlns:tenderlove='http://tenderlovemaking.com/'>
    <tenderlove:foo awesome='true'>snuggles!</tenderlove:foo>
  </x>
eoxml

reader.each do |node|

  # node is an instance of Nokogiri::XML::Reader
  puts node.name

end

```
 Note that [`Nokogiri::XML::Reader#each`](reader#method-i-each) can only be called once!! Once the cursor moves through the entire document, you must parse the document again. So make sure that you capture any information you need during the first iteration.

 The [`Reader`](reader) parser is good for when you need the speed of a [`SAX`](sax) parser, but do not want to write a [`Document`](document) handler.

     ### Constants

   TYPE\_ATTRIBUTE   Attribute node type

  TYPE\_CDATA   [`CDATA`](cdata) node type

  TYPE\_COMMENT   [`Comment`](comment) node type

  TYPE\_DOCUMENT   [`Document`](document) node type

  TYPE\_DOCUMENT\_FRAGMENT   [`Document`](document) Fragment node type

  TYPE\_DOCUMENT\_TYPE   [`Document`](document) Type node type

  TYPE\_ELEMENT   [`Element`](element) node type

  TYPE\_END\_ELEMENT   [`Element`](element) end node type

  TYPE\_END\_ENTITY   Entity end node type

  TYPE\_ENTITY   Entity node type

  TYPE\_ENTITY\_REFERENCE   Entity Reference node type

  TYPE\_NONE  TYPE\_NOTATION   [`Notation`](notation) node type

  TYPE\_PROCESSING\_INSTRUCTION   PI node type

  TYPE\_SIGNIFICANT\_WHITESPACE   Significant Whitespace node type

  TYPE\_TEXT   [`Text`](text) node type

  TYPE\_WHITESPACE   Whitespace node type

  TYPE\_XML\_DECLARATION   [`XML`](../xml) Declaration node type

      ### Attributes

    errors[RW]   A list of errors encountered while parsing

     source[R]   The [`XML`](../xml) source

      ### Public Class Methods

      from\_io(io, url = nil, encoding = nil, options = 0)  Show source   
 
```
static VALUE
from_io(int argc, VALUE *argv, VALUE klass)
{
  VALUE rb_io, rb_url, encoding, rb_options;
  xmlTextReaderPtr reader;
  const char *c_url      = NULL;
  const char *c_encoding = NULL;
  int c_options           = 0;
  VALUE rb_reader, args[3];

  rb_scan_args(argc, argv, "13", &rb_io, &rb_url, &encoding, &rb_options);

  if (!RTEST(rb_io)) { rb_raise(rb_eArgError, "io cannot be nil"); }
  if (RTEST(rb_url)) { c_url = StringValueCStr(rb_url); }
  if (RTEST(encoding)) { c_encoding = StringValueCStr(encoding); }
  if (RTEST(rb_options)) { c_options = (int)NUM2INT(rb_options); }

  reader = xmlReaderForIO(
             (xmlInputReadCallback)noko_io_read,
             (xmlInputCloseCallback)noko_io_close,
             (void *)rb_io,
             c_url,
             c_encoding,
             c_options
           );

  if (reader == NULL) {
    xmlFreeTextReader(reader);
    rb_raise(rb_eRuntimeError, "couldn't create a parser");
  }

  rb_reader = Data_Wrap_Struct(klass, NULL, dealloc, reader);
  args[0] = rb_io;
  args[1] = rb_url;
  args[2] = encoding;
  rb_obj_call_init(rb_reader, 3, args);

  return rb_reader;
}
```
  Create a new reader that parses `io`

       from\_memory(string, url = nil, encoding = nil, options = 0)  Show source   
 
```
static VALUE
from_memory(int argc, VALUE *argv, VALUE klass)
{
  VALUE rb_buffer, rb_url, encoding, rb_options;
  xmlTextReaderPtr reader;
  const char *c_url      = NULL;
  const char *c_encoding = NULL;
  int c_options           = 0;
  VALUE rb_reader, args[3];

  rb_scan_args(argc, argv, "13", &rb_buffer, &rb_url, &encoding, &rb_options);

  if (!RTEST(rb_buffer)) { rb_raise(rb_eArgError, "string cannot be nil"); }
  if (RTEST(rb_url)) { c_url = StringValueCStr(rb_url); }
  if (RTEST(encoding)) { c_encoding = StringValueCStr(encoding); }
  if (RTEST(rb_options)) { c_options = (int)NUM2INT(rb_options); }

  reader = xmlReaderForMemory(
             StringValuePtr(rb_buffer),
             (int)RSTRING_LEN(rb_buffer),
             c_url,
             c_encoding,
             c_options
           );

  if (reader == NULL) {
    xmlFreeTextReader(reader);
    rb_raise(rb_eRuntimeError, "couldn't create a parser");
  }

  rb_reader = Data_Wrap_Struct(klass, NULL, dealloc, reader);
  args[0] = rb_buffer;
  args[1] = rb_url;
  args[2] = encoding;
  rb_obj_call_init(rb_reader, 3, args);

  return rb_reader;
}
```
  Create a new reader that parses `string`

      ### Public Instance Methods

      attribute(name)  Show source   
 
```
static VALUE
reader_attribute(VALUE self, VALUE name)
{
  xmlTextReaderPtr reader;
  xmlChar *value ;
  VALUE rb_value;

  Data_Get_Struct(self, xmlTextReader, reader);

  if (NIL_P(name)) { return Qnil; }
  name = StringValue(name) ;

  value = xmlTextReaderGetAttribute(reader, (xmlChar *)StringValueCStr(name));
  if (value == NULL) { return Qnil; }

  rb_value = NOKOGIRI_STR_NEW2(value);
  xmlFree(value);
  return rb_value;
}
```
  Get the value of attribute named `name`

       attribute\_at(index)  Show source   
 
```
static VALUE
attribute_at(VALUE self, VALUE index)
{
  xmlTextReaderPtr reader;
  xmlChar *value;
  VALUE rb_value;

  Data_Get_Struct(self, xmlTextReader, reader);

  if (NIL_P(index)) { return Qnil; }
  index = rb_Integer(index);

  value = xmlTextReaderGetAttributeNo(
            reader,
            (int)NUM2INT(index)
          );
  if (value == NULL) { return Qnil; }

  rb_value = NOKOGIRI_STR_NEW2(value);
  xmlFree(value);
  return rb_value;
}
```
  Get the value of attribute at `index`

       attribute\_count  Show source   
 
```
static VALUE
attribute_count(VALUE self)
{
  xmlTextReaderPtr reader;
  int count;

  Data_Get_Struct(self, xmlTextReader, reader);
  count = xmlTextReaderAttributeCount(reader);
  if (count == -1) { return Qnil; }

  return INT2NUM(count);
}
```
  Get the number of attributes for the current node

       attribute\_hash() → Hash<String ⇒ String>  Show source   
 
```
static VALUE
rb_xml_reader_attribute_hash(VALUE rb_reader)
{
  VALUE rb_attributes = rb_hash_new();
  xmlTextReaderPtr c_reader;
  xmlNodePtr c_node;
  xmlAttrPtr c_property;
  VALUE rb_errors;

  Data_Get_Struct(rb_reader, xmlTextReader, c_reader);

  if (!has_attributes(c_reader)) {
    return rb_attributes;
  }

  rb_errors = rb_funcall(rb_reader, rb_intern("errors"), 0);

  xmlSetStructuredErrorFunc((void *)rb_errors, Nokogiri_error_array_pusher);
  c_node = xmlTextReaderExpand(c_reader);
  xmlSetStructuredErrorFunc(NULL, NULL);

  if (c_node == NULL) {
    if (RARRAY_LEN(rb_errors) > 0) {
      VALUE rb_error = rb_ary_entry(rb_errors, 0);
      VALUE exception_message = rb_funcall(rb_error, rb_intern("to_s"), 0);
      rb_exc_raise(rb_class_new_instance(1, &exception_message, cNokogiriXmlSyntaxError));
    }
    return Qnil;
  }

  c_property = c_node->properties;
  while (c_property != NULL) {
    VALUE rb_name = NOKOGIRI_STR_NEW2(c_property->name);
    VALUE rb_value = Qnil;
    xmlChar *c_value = xmlNodeGetContent((xmlNode *)c_property);

    if (c_value) {
      rb_value = NOKOGIRI_STR_NEW2(c_value);
      xmlFree(c_value);
    }

    rb_hash_aset(rb_attributes, rb_name, rb_value);

    c_property = c_property->next;
  }

  return rb_attributes;
}
```
  Get the attributes of the current node as a Hash of names and values.

 See related: [`#attributes`](reader#method-i-attributes) and [`#namespaces`](reader#method-i-namespaces)

       attribute\_nodes() → Array<Nokogiri::XML::Attr>  Show source   
 
```
static VALUE
rb_xml_reader_attribute_nodes(VALUE rb_reader)
{
  xmlTextReaderPtr c_reader;
  xmlNodePtr c_node;
  VALUE attr_nodes;
  int j;

  // TODO: deprecated, remove in Nokogiri v1.15, see https://github.com/sparklemotion/nokogiri/issues/2598
  // After removal, we can also remove all the "node_has_a_document" special handling from xml_node.c
  NOKO_WARN_DEPRECATION("Reader#attribute_nodes is deprecated and will be removed in a future version of Nokogiri. Please use Reader#attribute_hash instead.");

  Data_Get_Struct(rb_reader, xmlTextReader, c_reader);

  if (! has_attributes(c_reader)) {
    return rb_ary_new() ;
  }

  c_node = xmlTextReaderExpand(c_reader);
  if (c_node == NULL) {
    return Qnil;
  }

  attr_nodes = noko_xml_node_attrs(c_node);

  /* ensure that the Reader won't be GCed as long as a node is referenced */
  for (j = 0 ; j < RARRAY_LEN(attr_nodes) ; j++) {
    rb_iv_set(rb_ary_entry(attr_nodes, j), "@reader", rb_reader);
  }

  return attr_nodes;
}
```
  Get the attributes of the current node as an Array of XML:Attr

 ⚠ This method is deprecated and unsafe to use. It will be removed in a future version of [`Nokogiri`](../../nokogiri).

 See related: [`#attribute_hash`](reader#method-i-attribute_hash), [`#attributes`](reader#method-i-attributes)

      attributes() Show source   
 
```
# File lib/nokogiri/xml/reader.rb, line 92
def attributes
  attribute_hash.merge(namespaces)
end
```
  Get the attributes and namespaces of the current node as a Hash.

 This is the union of [`Reader#attribute_hash`](reader#method-i-attribute_hash) and [`Reader#namespaces`](reader#method-i-namespaces)

  Returns   (Hash<String, String>) Attribute names and values, and namespace prefixes and hrefs.

         attributes?  Show source   
 
```
static VALUE
attributes_eh(VALUE self)
{
  xmlTextReaderPtr reader;
  int eh;

  Data_Get_Struct(self, xmlTextReader, reader);
  eh = has_attributes(reader);
  if (eh == 0) { return Qfalse; }
  if (eh == 1) { return Qtrue; }

  return Qnil;
}
```
  Does this node have attributes?

       base\_uri  Show source   
 
```
static VALUE
rb_xml_reader_base_uri(VALUE rb_reader)
{
  VALUE rb_base_uri;
  xmlTextReaderPtr c_reader;
  xmlChar *c_base_uri;

  Data_Get_Struct(rb_reader, xmlTextReader, c_reader);

  c_base_uri = xmlTextReaderBaseUri(c_reader);
  if (c_base_uri == NULL) {
    return Qnil;
  }

  rb_base_uri = NOKOGIRI_STR_NEW2(c_base_uri);
  xmlFree(c_base_uri);

  return rb_base_uri;
}
```
  Get the xml:base of the node

       default?  Show source   
 
```
static VALUE
default_eh(VALUE self)
{
  xmlTextReaderPtr reader;
  int eh;

  Data_Get_Struct(self, xmlTextReader, reader);
  eh = xmlTextReaderIsDefault(reader);
  if (eh == 0) { return Qfalse; }
  if (eh == 1) { return Qtrue; }

  return Qnil;
}
```
  Was an attribute generated from the default value in the [`DTD`](dtd) or schema?

       depth  Show source   
 
```
static VALUE
depth(VALUE self)
{
  xmlTextReaderPtr reader;
  int depth;

  Data_Get_Struct(self, xmlTextReader, reader);
  depth = xmlTextReaderDepth(reader);
  if (depth == -1) { return Qnil; }

  return INT2NUM(depth);
}
```
  Get the depth of the node

      each() { |cursor| ... } Show source   
 
```
# File lib/nokogiri/xml/reader.rb, line 98
def each
  while (cursor = read)
    yield cursor
  end
end
```
  Move the cursor through the document yielding the cursor to the block

       empty\_element? # → true or false  Show source   
 
```
static VALUE
empty_element_p(VALUE self)
{
  xmlTextReaderPtr reader;

  Data_Get_Struct(self, xmlTextReader, reader);

  if (xmlTextReaderIsEmptyElement(reader)) {
    return Qtrue;
  }

  return Qfalse;
}
```
  Returns true if the current node is empty, otherwise false.

   Also aliased as: [self\_closing?](reader#method-i-self_closing-3F)      encoding() Show source   
 
```
static VALUE
rb_xml_reader_encoding(VALUE rb_reader)
{
  xmlTextReaderPtr c_reader;
  const char *parser_encoding;
  VALUE constructor_encoding;

  constructor_encoding = rb_iv_get(rb_reader, "@encoding");
  if (RTEST(constructor_encoding)) {
    return constructor_encoding;
  }

  Data_Get_Struct(rb_reader, xmlTextReader, c_reader);
  parser_encoding = (const char *)xmlTextReaderConstEncoding(c_reader);
  if (parser_encoding == NULL) { return Qnil; }
  return NOKOGIRI_STR_NEW2(parser_encoding);
}
```
        inner\_xml  Show source   
 
```
static VALUE
inner_xml(VALUE self)
{
  xmlTextReaderPtr reader;
  xmlChar *value;
  VALUE str;

  Data_Get_Struct(self, xmlTextReader, reader);

  value = xmlTextReaderReadInnerXml(reader);

  str = Qnil;
  if (value) {
    str = NOKOGIRI_STR_NEW2((char *)value);
    xmlFree(value);
  }

  return str;
}
```
  Read the contents of the current node, including child nodes and markup. Returns a utf-8 encoded string.

       lang  Show source   
 
```
static VALUE
lang(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *lang;

  Data_Get_Struct(self, xmlTextReader, reader);
  lang = (const char *)xmlTextReaderConstXmlLang(reader);
  if (lang == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(lang);
}
```
  Get the xml:lang scope within which the node resides.

       local\_name  Show source   
 
```
static VALUE
local_name(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *name;

  Data_Get_Struct(self, xmlTextReader, reader);
  name = (const char *)xmlTextReaderConstLocalName(reader);
  if (name == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(name);
}
```
  Get the local name of the node

       name  Show source   
 
```
static VALUE
name(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *name;

  Data_Get_Struct(self, xmlTextReader, reader);
  name = (const char *)xmlTextReaderConstName(reader);
  if (name == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(name);
}
```
  Get the name of the node. Returns a utf-8 encoded string.

       namespace\_uri  Show source   
 
```
static VALUE
namespace_uri(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *uri;

  Data_Get_Struct(self, xmlTextReader, reader);
  uri = (const char *)xmlTextReaderConstNamespaceUri(reader);
  if (uri == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(uri);
}
```
  Get the URI defining the namespace associated with the node

       namespaces  Show source   
 
```
static VALUE
rb_xml_reader_namespaces(VALUE rb_reader)
{
  VALUE rb_namespaces = rb_hash_new() ;
  xmlTextReaderPtr c_reader;
  xmlNodePtr c_node;
  VALUE rb_errors;

  Data_Get_Struct(rb_reader, xmlTextReader, c_reader);

  if (! has_attributes(c_reader)) {
    return rb_namespaces ;
  }

  rb_errors = rb_funcall(rb_reader, rb_intern("errors"), 0);

  xmlSetStructuredErrorFunc((void *)rb_errors, Nokogiri_error_array_pusher);
  c_node = xmlTextReaderExpand(c_reader);
  xmlSetStructuredErrorFunc(NULL, NULL);

  if (c_node == NULL) {
    if (RARRAY_LEN(rb_errors) > 0) {
      VALUE rb_error = rb_ary_entry(rb_errors, 0);
      VALUE exception_message = rb_funcall(rb_error, rb_intern("to_s"), 0);
      rb_exc_raise(rb_class_new_instance(1, &exception_message, cNokogiriXmlSyntaxError));
    }
    return Qnil;
  }

  Nokogiri_xml_node_namespaces(c_node, rb_namespaces);

  return rb_namespaces ;
}
```
  Get a hash of namespaces for this [`Node`](node)

       node\_type  Show source   
 
```
static VALUE
node_type(VALUE self)
{
  xmlTextReaderPtr reader;
  Data_Get_Struct(self, xmlTextReader, reader);
  return INT2NUM(xmlTextReaderNodeType(reader));
}
```
  Get the type of readers current node

       outer\_xml  Show source   
 
```
static VALUE
outer_xml(VALUE self)
{
  xmlTextReaderPtr reader;
  xmlChar *value;
  VALUE str = Qnil;

  Data_Get_Struct(self, xmlTextReader, reader);

  value = xmlTextReaderReadOuterXml(reader);

  if (value) {
    str = NOKOGIRI_STR_NEW2((char *)value);
    xmlFree(value);
  }
  return str;
}
```
  Read the current node and its contents, including child nodes and markup. Returns a utf-8 encoded string.

       prefix  Show source   
 
```
static VALUE
prefix(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *prefix;

  Data_Get_Struct(self, xmlTextReader, reader);
  prefix = (const char *)xmlTextReaderConstPrefix(reader);
  if (prefix == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(prefix);
}
```
  Get the shorthand reference to the namespace associated with the node.

       read  Show source   
 
```
static VALUE
read_more(VALUE self)
{
  xmlTextReaderPtr reader;
  xmlErrorPtr error;
  VALUE error_list;
  int ret;

  Data_Get_Struct(self, xmlTextReader, reader);

  error_list = rb_funcall(self, rb_intern("errors"), 0);

  xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher);
  ret = xmlTextReaderRead(reader);
  xmlSetStructuredErrorFunc(NULL, NULL);

  if (ret == 1) { return self; }
  if (ret == 0) { return Qnil; }

  error = xmlGetLastError();
  if (error) {
    rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error));
  } else {
    rb_raise(rb_eRuntimeError, "Error pulling: %d", ret);
  }

  return Qnil;
}
```
  Move the [`Reader`](reader) forward through the [`XML`](../xml) document.

      self\_closing?()    Alias for: [empty\_element?](reader#method-i-empty_element-3F)       state  Show source   
 
```
static VALUE
state(VALUE self)
{
  xmlTextReaderPtr reader;
  Data_Get_Struct(self, xmlTextReader, reader);
  return INT2NUM(xmlTextReaderReadState(reader));
}
```
  Get the state of the reader

       value  Show source   
 
```
static VALUE
value(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *value;

  Data_Get_Struct(self, xmlTextReader, reader);
  value = (const char *)xmlTextReaderConstValue(reader);
  if (value == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(value);
}
```
  Get the text value of the node if present. Returns a utf-8 encoded string.

       value?  Show source   
 
```
static VALUE
value_eh(VALUE self)
{
  xmlTextReaderPtr reader;
  int eh;

  Data_Get_Struct(self, xmlTextReader, reader);
  eh = xmlTextReaderHasValue(reader);
  if (eh == 0) { return Qfalse; }
  if (eh == 1) { return Qtrue; }

  return Qnil;
}
```
  Does this node have a text value?

       xml\_version  Show source   
 
```
static VALUE
xml_version(VALUE self)
{
  xmlTextReaderPtr reader;
  const char *version;

  Data_Get_Struct(self, xmlTextReader, reader);
  version = (const char *)xmlTextReaderConstXmlVersion(reader);
  if (version == NULL) { return Qnil; }

  return NOKOGIRI_STR_NEW2(version);
}
```
  Get the [`XML`](../xml) version of the document being read

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Reader.html>

class Nokogiri::XML::RelaxNG
=============================



Parent:
cNokogiriXmlSchema
  [`Nokogiri::XML::RelaxNG`](relaxng) is used for validating [`XML`](../xml) against a [`RelaxNG`](relaxng) schema.

 Synopsis
--------

 Validate an [`XML`](../xml) document against a [`RelaxNG`](relaxng) schema. Loop over the errors that are returned and print them out:

 
```
schema  = Nokogiri::XML::RelaxNG(File.open(ADDRESS_SCHEMA_FILE))
doc     = Nokogiri::XML(File.open(ADDRESS_XML_FILE))

schema.validate(doc).each do |error|
  puts error.message
end

```
 The list of errors are [`Nokogiri::XML::SyntaxError`](syntaxerror) objects.

 NOTE: [`RelaxNG`](relaxng) input is always treated as TRUSTED documents, meaning that they will cause the underlying parsing libraries to access network resources. This is counter to Nokogiri’s “untrusted by default” security policy, but is a limitation of the underlying libraries.

     ### Public Class Methods

      from\_document(doc)  Show source   
 
```
static VALUE
from_document(int argc, VALUE *argv, VALUE klass)
{
  VALUE document;
  VALUE parse_options;
  xmlDocPtr doc;
  xmlRelaxNGParserCtxtPtr ctx;
  xmlRelaxNGPtr schema;
  VALUE errors;
  VALUE rb_schema;
  int scanned_args = 0;

  scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options);

  Data_Get_Struct(document, xmlDoc, doc);
  doc = doc->doc; /* In case someone passes us a node. ugh. */

  if (scanned_args == 1) {
    parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
  }

  ctx = xmlRelaxNGNewDocParserCtxt(doc);

  errors = rb_ary_new();
  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);

#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
  xmlRelaxNGSetParserStructuredErrors(
    ctx,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  schema = xmlRelaxNGParse(ctx);

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlRelaxNGFreeParserCtxt(ctx);

  if (NULL == schema) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      Nokogiri_error_raise(NULL, error);
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
  rb_iv_set(rb_schema, "@errors", errors);
  rb_iv_set(rb_schema, "@parse_options", parse_options);

  return rb_schema;
}
```
  Create a new [`RelaxNG`](relaxng) schema from the [`Nokogiri::XML::Document`](document) `doc`

       read\_memory(string)  Show source   
 
```
static VALUE
read_memory(int argc, VALUE *argv, VALUE klass)
{
  VALUE content;
  VALUE parse_options;
  xmlRelaxNGParserCtxtPtr ctx;
  xmlRelaxNGPtr schema;
  VALUE errors;
  VALUE rb_schema;
  int scanned_args = 0;

  scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options);
  if (scanned_args == 1) {
    parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
  }

  ctx = xmlRelaxNGNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content));

  errors = rb_ary_new();
  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);

#ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS
  xmlRelaxNGSetParserStructuredErrors(
    ctx,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  schema = xmlRelaxNGParse(ctx);

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlRelaxNGFreeParserCtxt(ctx);

  if (NULL == schema) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      Nokogiri_error_raise(NULL, error);
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
  rb_iv_set(rb_schema, "@errors", errors);
  rb_iv_set(rb_schema, "@parse_options", parse_options);

  return rb_schema;
}
```
  Create a new [`RelaxNG`](relaxng) from the contents of `string`

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/RelaxNG.html>

module Nokogiri::XML::SAX
==========================

  [`SAX`](sax) Parsers are event driven parsers. [`Nokogiri`](../../nokogiri) provides two different event based parsers when dealing with [`XML`](../xml). If you want to do [`SAX`](sax) style parsing using [`HTML`](../html4), check out [`Nokogiri::HTML4::SAX`](../html4/sax).

 The basic way a [`SAX`](sax) style parser works is by creating a parser, telling the parser about the events we’re interested in, then giving the parser some [`XML`](../xml) to process. The parser will notify you when it encounters events you said you would like to know about.

 To register for events, you simply subclass [`Nokogiri::XML::SAX::Document`](sax/document), and implement the methods for which you would like notification.

 For example, if I want to be notified when a document ends, and when an element starts, I would write a class like this:

 
```
class MyDocument < Nokogiri::XML::SAX::Document
  def end_document
    puts "the document has ended"
  end

  def start_element name, attributes = []
    puts "#{name} started"
  end
end

```
 Then I would instantiate a [`SAX`](sax) parser with this document, and feed the parser some [`XML`](../xml)

 
```
# Create a new parser
parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new)

# Feed the parser some XML
parser.parse(File.open(ARGV[0]))

```
 Now my document handler will be called when each node starts, and when then document ends. To see what kinds of events are available, take a look at [`Nokogiri::XML::SAX::Document`](sax/document).

 Two [`SAX`](sax) parsers for [`XML`](../xml) are available, a parser that reads from a string or IO object as it feels necessary, and a parser that lets you spoon feed it [`XML`](../xml). If you want to let [`Nokogiri`](../../nokogiri) deal with reading your [`XML`](../xml), use the [`Nokogiri::XML::SAX::Parser`](sax/parser). If you want to have fine grain control over the [`XML`](../xml) input, use the [`Nokogiri::XML::SAX::PushParser`](sax/pushparser).

  

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SAX.html>

class Nokogiri::XML::SAX::Document
===================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  This class is used for registering types of events you are interested in handling. All of the methods on this class are available as possible events while parsing an [`XML`](../../xml) document. To register for any particular event, just subclass this class and implement the methods you are interested in knowing about.

 To only be notified about start and end element events, write a class like this:

 
```
class MyDocument < Nokogiri::XML::SAX::Document
  def start_element name, attrs = []
    puts "#{name} started!"
  end

  def end_element name
    puts "#{name} ended"
  end
end

```
 You can use this event handler for any [`SAX`](../sax) style parser included with [`Nokogiri`](../../../nokogiri). See [`Nokogiri::XML::SAX`](../sax), and [`Nokogiri::HTML4::SAX`](../../html4/sax).

     ### Public Instance Methods

     cdata\_block(string) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 155
def cdata_block(string)
end
```
  Called when cdata blocks are found `string` contains the cdata content

      characters(string) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 131
def characters(string)
end
```
  Characters read between a tag. This method might be called multiple times given one contiguous string of characters.

 `string` contains the character data

      comment(string) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 137
def comment(string)
end
```
  Called when comments are encountered `string` contains the comment data

      end\_document() Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 79
def end_document
end
```
  Called when document ends parsing

      end\_element(name) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 93
def end_element(name)
end
```
  Called at the end of an element `name` is the tag name

      end\_element\_namespace(name, prefix = nil, uri = nil) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 120
def end_element_namespace(name, prefix = nil, uri = nil)
  ###
  # Deal with SAX v1 interface
  end_element([prefix, name].compact.join(":"))
end
```
  Called at the end of an element `name` is the element’s name `prefix` is the namespace prefix associated with the element `uri` is the associated namespace URI

      error(string) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 149
def error(string)
end
```
  Called on document errors `string` contains the error

      processing\_instruction(name, content) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 162
def processing_instruction(name, content)
end
```
  Called when processing instructions are found `name` is the target of the instruction `content` is the value of the instruction

      start\_document() Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 74
def start_document
end
```
  Called when document starts parsing

      start\_element(name, attrs = []) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 87
def start_element(name, attrs = [])
end
```
  Called at the beginning of an element

 * `name` is the name of the tag
* `attrs` are an assoc list of namespaces and attributes, e.g.:

 
```
[ ["xmlns:foo", "http://sample.net"], ["size", "large"] ]

```

      start\_element\_namespace(name, attrs = [], prefix = nil, uri = nil, ns = []) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 103
def start_element_namespace(name, attrs = [], prefix = nil, uri = nil, ns = [])
  ###
  # Deal with SAX v1 interface
  name = [prefix, name].compact.join(":")
  attributes = ns.map do |ns_prefix, ns_uri|
    [["xmlns", ns_prefix].compact.join(":"), ns_uri]
  end + attrs.map do |attr|
    [[attr.prefix, attr.localname].compact.join(":"), attr.value]
  end
  start_element(name, attributes)
end
```
  Called at the beginning of an element `name` is the element name `attrs` is a list of attributes `prefix` is the namespace prefix for the element `uri` is the associated namespace URI `ns` is a hash of namespace prefix:urls associated with the element

      warning(string) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 143
def warning(string)
end
```
  Called on document warnings `string` contains the warning

      xmldecl(version, encoding, standalone) Show source   
 
```
# File lib/nokogiri/xml/sax/document.rb, line 69
def xmldecl(version, encoding, standalone)
end
```
  Called when an [`XML`](../../xml) declaration is parsed

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SAX/Document.html>

class Nokogiri::XML::SAX::Parser
=================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  This parser is a [`SAX`](../sax) style parser that reads it’s input as it deems necessary. The parser takes a [`Nokogiri::XML::SAX::Document`](document), an optional encoding, then given an [`XML`](../../xml) input, sends messages to the [`Nokogiri::XML::SAX::Document`](document).

 Here is an example of using this parser:

 
```
# Create a subclass of Nokogiri::XML::SAX::Document and implement
# the events we care about:
class MyDoc < Nokogiri::XML::SAX::Document
  def start_element name, attrs = []
    puts "starting: #{name}"
  end

  def end_element name
    puts "ending: #{name}"
  end
end

# Create our parser
parser = Nokogiri::XML::SAX::Parser.new(MyDoc.new)

# Send some XML to the parser
parser.parse(File.open(ARGV[0]))

```
 For more information about [`SAX`](../sax) parsers, see [`Nokogiri::XML::SAX`](../sax). Also see [`Nokogiri::XML::SAX::Document`](document) for the available events.

     ### Constants

   ENCODINGS   Encodinds this parser supports

      ### Attributes

    document[RW]   The [`Nokogiri::XML::SAX::Document`](document) where events will be sent.

     encoding[RW]   The encoding beings used for this document.

      ### Public Class Methods

     new(doc = Nokogiri::XML::SAX::Document.new, encoding = "UTF-8") Show source   
 
```
# File lib/nokogiri/xml/sax/parser.rb, line 72
def initialize(doc = Nokogiri::XML::SAX::Document.new, encoding = "UTF-8")
  @encoding = check_encoding(encoding)
  @document = doc
  @warned   = false
end
```
  Create a new [`Parser`](parser) with `doc` and `encoding`

      ### Public Instance Methods

     parse(thing, &block) Show source   
 
```
# File lib/nokogiri/xml/sax/parser.rb, line 81
def parse(thing, &block)
  if thing.respond_to?(:read) && thing.respond_to?(:close)
    parse_io(thing, &block)
  else
    parse_memory(thing, &block)
  end
end
```
  Parse given `thing` which may be a string containing xml, or an IO object.

      parse\_file(filename) { |ctx| ... } Show source   
 
```
# File lib/nokogiri/xml/sax/parser.rb, line 99
def parse_file(filename)
  raise ArgumentError unless filename
  raise Errno::ENOENT unless File.exist?(filename)
  raise Errno::EISDIR if File.directory?(filename)

  ctx = ParserContext.file(filename)
  yield ctx if block_given?
  ctx.parse_with(self)
end
```
  Parse a file with `filename`

      parse\_io(io, encoding = @encoding) { |ctx| ... } Show source   
 
```
# File lib/nokogiri/xml/sax/parser.rb, line 91
def parse_io(io, encoding = @encoding)
  ctx = ParserContext.io(io, ENCODINGS[check_encoding(encoding)])
  yield ctx if block_given?
  ctx.parse_with(self)
end
```
  Parse given `io`

      parse\_memory(data) { |ctx| ... } Show source   
 
```
# File lib/nokogiri/xml/sax/parser.rb, line 109
def parse_memory(data)
  ctx = ParserContext.memory(data)
  yield ctx if block_given?
  ctx.parse_with(self)
end
```
     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SAX/Parser.html>

class Nokogiri::XML::SAX::Parser::Attribute
============================================



Parent:
Struct.new(:localname, :prefix, :uri, :value)
 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SAX/Parser/Attribute.html>

class Nokogiri::XML::SAX::ParserContext
========================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  Context for [`XML`](../../xml) [`SAX`](../sax) parsers. This class is usually not instantiated by the user. Instead, you should be looking at [`Nokogiri::XML::SAX::Parser`](parser)

     ### Public Class Methods

      parse\_file(filename)  Show source   
 
```
static VALUE
parse_file(VALUE klass, VALUE filename)
{
  xmlParserCtxtPtr ctxt = xmlCreateFileParserCtxt(StringValueCStr(filename));
  return Data_Wrap_Struct(klass, NULL, deallocate, ctxt);
}
```
  Parse file given `filename`

       parse\_io(io, encoding)  Show source   
 
```
static VALUE
parse_io(VALUE klass, VALUE io, VALUE encoding)
{
  xmlParserCtxtPtr ctxt;
  xmlCharEncoding enc = (xmlCharEncoding)NUM2INT(encoding);

  if (!rb_respond_to(io, id_read)) {
    rb_raise(rb_eTypeError, "argument expected to respond to :read");
  }

  ctxt = xmlCreateIOParserCtxt(NULL, NULL,
                               (xmlInputReadCallback)noko_io_read,
                               (xmlInputCloseCallback)noko_io_close,
                               (void *)io, enc);
  if (ctxt->sax) {
    xmlFree(ctxt->sax);
    ctxt->sax = NULL;
  }

  return Data_Wrap_Struct(klass, NULL, deallocate, ctxt);
}
```
  Parse `io` object with `encoding`

       parse\_memory(data)  Show source   
 
```
static VALUE
parse_memory(VALUE klass, VALUE data)
{
  xmlParserCtxtPtr ctxt;

  Check_Type(data, T_STRING);

  if (!(int)RSTRING_LEN(data)) {
    rb_raise(rb_eRuntimeError, "data cannot be empty");
  }

  ctxt = xmlCreateMemoryParserCtxt(StringValuePtr(data),
                                   (int)RSTRING_LEN(data));
  if (ctxt->sax) {
    xmlFree(ctxt->sax);
    ctxt->sax = NULL;
  }

  return Data_Wrap_Struct(klass, NULL, deallocate, ctxt);
}
```
  Parse the [`XML`](../../xml) stored in memory in `data`

      new(thing, encoding = "UTF-8") Show source   
 
```
# File lib/nokogiri/xml/sax/parser_context.rb, line 11
def self.new(thing, encoding = "UTF-8")
  if [:read, :close].all? { |x| thing.respond_to?(x) }
    io(thing, Parser::ENCODINGS[encoding])
  else
    memory(thing)
  end
end
```
       ### Public Instance Methods

      column  Show source   
 
```
static VALUE
column(VALUE self)
{
  xmlParserCtxtPtr ctxt;
  xmlParserInputPtr io;

  Data_Get_Struct(self, xmlParserCtxt, ctxt);

  io = ctxt->input;
  if (io) {
    return INT2NUM(io->col);
  }

  return Qnil;
}
```
  Get the current column the parser context is processing.

       line  Show source   
 
```
static VALUE
line(VALUE self)
{
  xmlParserCtxtPtr ctxt;
  xmlParserInputPtr io;

  Data_Get_Struct(self, xmlParserCtxt, ctxt);

  io = ctxt->input;
  if (io) {
    return INT2NUM(io->line);
  }

  return Qnil;
}
```
  Get the current line the parser context is processing.

       parse\_with(sax\_handler)  Show source   
 
```
static VALUE
parse_with(VALUE self, VALUE sax_handler)
{
  xmlParserCtxtPtr ctxt;
  xmlSAXHandlerPtr sax;

  if (!rb_obj_is_kind_of(sax_handler, cNokogiriXmlSaxParser)) {
    rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::SAX::Parser");
  }

  Data_Get_Struct(self, xmlParserCtxt, ctxt);
  Data_Get_Struct(sax_handler, xmlSAXHandler, sax);

  /* Free the sax handler since we'll assign our own */
  if (ctxt->sax && ctxt->sax != (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) {
    xmlFree(ctxt->sax);
  }

  ctxt->sax = sax;
  ctxt->userData = (void *)NOKOGIRI_SAX_TUPLE_NEW(ctxt, sax_handler);

  xmlSetStructuredErrorFunc(NULL, NULL);

  rb_ensure(parse_doc, (VALUE)ctxt, parse_doc_finalize, (VALUE)ctxt);

  return Qnil;
}
```
  Use `sax_handler` and parse the current document

       recovery  Show source   
 
```
static VALUE
get_recovery(VALUE self)
{
  xmlParserCtxtPtr ctxt;
  Data_Get_Struct(self, xmlParserCtxt, ctxt);

  if (ctxt->recovery == 0) {
    return Qfalse;
  } else {
    return Qtrue;
  }
}
```
  Should this parser recover from structural errors? It will not stop processing file on structural errors if set to true

       recovery=(boolean)  Show source   
 
```
static VALUE
set_recovery(VALUE self, VALUE value)
{
  xmlParserCtxtPtr ctxt;
  Data_Get_Struct(self, xmlParserCtxt, ctxt);

  if (value == Qfalse) {
    ctxt->recovery = 0;
  } else {
    ctxt->recovery = 1;
  }

  return value;
}
```
  Should this parser recover from structural errors? It will not stop processing file on structural errors if set to true

       replace\_entities  Show source   
 
```
static VALUE
get_replace_entities(VALUE self)
{
  xmlParserCtxtPtr ctxt;
  Data_Get_Struct(self, xmlParserCtxt, ctxt);

  if (0 == ctxt->replaceEntities) {
    return Qfalse;
  } else {
    return Qtrue;
  }
}
```
  Should this parser replace entities? &amp; will get converted to ‘&’ if set to true

       replace\_entities=(boolean)  Show source   
 
```
static VALUE
set_replace_entities(VALUE self, VALUE value)
{
  xmlParserCtxtPtr ctxt;
  Data_Get_Struct(self, xmlParserCtxt, ctxt);

  if (Qfalse == value) {
    ctxt->replaceEntities = 0;
  } else {
    ctxt->replaceEntities = 1;
  }

  return value;
}
```
  Should this parser replace entities? &amp; will get converted to ‘&’ if set to true

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SAX/ParserContext.html>

class Nokogiri::XML::SAX::PushParser
=====================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  [`PushParser`](pushparser) can parse a document that is fed to it manually. It must be given a [`SAX::Document`](document) object which will be called with [`SAX`](../sax) events as the document is being parsed.

 Calling [`PushParser#<<`](pushparser#method-i-3C-3C) writes [`XML`](../../xml) to the parser, calling any [`SAX`](../sax) callbacks it can.

 [`PushParser#finish`](pushparser#method-i-finish) tells the parser that the document is finished and calls the end\_document [`SAX`](../sax) method.

 Example:

 
```
parser = PushParser.new(Class.new(XML::SAX::Document) {
  def start_document
    puts "start document called"
  end
}.new)
parser << "<div>hello<"
parser << "/div>"
parser.finish

```
     ### Attributes

    document[RW]   The [`Nokogiri::XML::SAX::Document`](document) on which the [`PushParser`](pushparser) will be operating

      ### Public Class Methods

     new(doc = XML::SAX::Document.new, file\_name = nil, encoding = "UTF-8") Show source   
 
```
# File lib/nokogiri/xml/sax/push_parser.rb, line 35
def initialize(doc = XML::SAX::Document.new, file_name = nil, encoding = "UTF-8")
  @document = doc
  @encoding = encoding
  @sax_parser = XML::SAX::Parser.new(doc)

  ## Create our push parser context
  initialize_native(@sax_parser, file_name)
end
```
  Create a new [`PushParser`](pushparser) with `doc` as the [`SAX`](../sax) [`Document`](document), providing an optional `file_name` and `encoding`

      ### Public Instance Methods

     <<(chunk, last\_chunk = false)    Alias for: [write](pushparser#method-i-write)      finish() Show source   
 
```
# File lib/nokogiri/xml/sax/push_parser.rb, line 55
def finish
  write("", true)
end
```
  Finish the parsing. This method is only necessary for [`Nokogiri::XML::SAX::Document#end_document`](document#method-i-end_document) to be called.

      options() Show source   
 
```
static VALUE
get_options(VALUE self)
{
  xmlParserCtxtPtr ctx;
  Data_Get_Struct(self, xmlParserCtxt, ctx);

  return INT2NUM(ctx->options);
}
```
       options=(p1) Show source   
 
```
static VALUE
set_options(VALUE self, VALUE options)
{
  xmlParserCtxtPtr ctx;
  Data_Get_Struct(self, xmlParserCtxt, ctx);

  if (xmlCtxtUseOptions(ctx, (int)NUM2INT(options)) != 0) {
    rb_raise(rb_eRuntimeError, "Cannot set XML parser context options");
  }

  return Qnil;
}
```
        replace\_entities  Show source   
 
```
static VALUE
get_replace_entities(VALUE self)
{
  xmlParserCtxtPtr ctx;
  Data_Get_Struct(self, xmlParserCtxt, ctx);

  if (0 == ctx->replaceEntities) {
    return Qfalse;
  } else {
    return Qtrue;
  }
}
```
  Should this parser replace entities? &amp; will get converted to ‘&’ if set to true

       replace\_entities=(boolean)  Show source   
 
```
static VALUE
set_replace_entities(VALUE self, VALUE value)
{
  xmlParserCtxtPtr ctx;
  Data_Get_Struct(self, xmlParserCtxt, ctx);

  if (Qfalse == value) {
    ctx->replaceEntities = 0;
  } else {
    ctx->replaceEntities = 1;
  }

  return value;
}
```
  Should this parser replace entities? &amp; will get converted to ‘&’ if set to true

      write(chunk, last\_chunk = false) Show source   
 
```
# File lib/nokogiri/xml/sax/push_parser.rb, line 47
def write(chunk, last_chunk = false)
  native_write(chunk, last_chunk)
end
```
  Write a `chunk` of [`XML`](../../xml) to the [`PushParser`](pushparser). Any callback methods that can be called will be called immediately.

   Also aliased as: [<<](pushparser#method-i-3C-3C)    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SAX/PushParser.html>

class Nokogiri::XML::Schema
============================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  [`Nokogiri::XML::Schema`](schema) is used for validating [`XML`](../xml) against a schema (usually from an xsd file).

 Synopsis
--------

 Validate an [`XML`](../xml) document against a [`Schema`](schema). Loop over the errors that are returned and print them out:

 
```
xsd = Nokogiri::XML::Schema(File.read(PO_SCHEMA_FILE))
doc = Nokogiri::XML(File.read(PO_XML_FILE))

xsd.validate(doc).each do |error|
  puts error.message
end

```
 The list of errors are [`Nokogiri::XML::SyntaxError`](syntaxerror) objects.

 NOTE: As of v1.11.0, [`Schema`](schema) treats inputs as UNTRUSTED by default, and so external entities are not resolved from the network (‘http://` or `ftp://`). Previously, parsing treated documents as “trusted” by default which was counter to Nokogiri’s “untrusted by default” security policy. If a document is trusted, then the caller may turn off the NONET option via the [`ParseOptions`](parseoptions) to re-enable external entity resolution over a network connection.

     ### Attributes

    errors[RW]   Errors while parsing the schema file

     parse\_options[RW]   The [`Nokogiri::XML::ParseOptions`](parseoptions) used to parse the schema

      ### Public Class Methods

      from\_document(doc)  Show source   
 
```
static VALUE
from_document(int argc, VALUE *argv, VALUE klass)
{
  VALUE document;
  VALUE parse_options;
  int parse_options_int;
  xmlDocPtr doc;
  xmlSchemaParserCtxtPtr ctx;
  xmlSchemaPtr schema;
  VALUE errors;
  VALUE rb_schema;
  int scanned_args = 0;
  xmlExternalEntityLoader old_loader = 0;

  scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options);

  Noko_Node_Get_Struct(document, xmlDoc, doc);
  doc = doc->doc; /* In case someone passes us a node. ugh. */

  if (scanned_args == 1) {
    parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
  }
  parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0));

  if (has_blank_nodes_p(DOC_NODE_CACHE(doc))) {
    rb_raise(rb_eArgError, "Creating a schema from a document that has blank nodes exposed to Ruby is dangerous");
  }

  ctx = xmlSchemaNewDocParserCtxt(doc);

  errors = rb_ary_new();
  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);

#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
  xmlSchemaSetParserStructuredErrors(
    ctx,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  if (parse_options_int & XML_PARSE_NONET) {
    old_loader = xmlGetExternalEntityLoader();
    xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader);
  }

  schema = xmlSchemaParse(ctx);

  if (old_loader) {
    xmlSetExternalEntityLoader(old_loader);
  }

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlSchemaFreeParserCtxt(ctx);

  if (NULL == schema) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      Nokogiri_error_raise(NULL, error);
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
  rb_iv_set(rb_schema, "@errors", errors);
  rb_iv_set(rb_schema, "@parse_options", parse_options);

  return rb_schema;

  return Qnil;
}
```
  Create a new [`Schema`](schema) from the [`Nokogiri::XML::Document`](document) `doc`

      new(string\_or\_io, options = ParseOptions::DEFAULT\_SCHEMA) Show source   
 
```
# File lib/nokogiri/xml/schema.rb, line 46
def self.new(string_or_io, options = ParseOptions::DEFAULT_SCHEMA)
  from_document(Nokogiri::XML(string_or_io), options)
end
```
  Create a new [`Nokogiri::XML::Schema`](schema) object using a `string_or_io` object.

       read\_memory(string)  Show source   
 
```
static VALUE
read_memory(int argc, VALUE *argv, VALUE klass)
{
  VALUE content;
  VALUE parse_options;
  int parse_options_int;
  xmlSchemaParserCtxtPtr ctx;
  xmlSchemaPtr schema;
  VALUE errors;
  VALUE rb_schema;
  int scanned_args = 0;
  xmlExternalEntityLoader old_loader = 0;

  scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options);
  if (scanned_args == 1) {
    parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA"));
  }
  parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0));

  ctx = xmlSchemaNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content));

  errors = rb_ary_new();
  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);

#ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS
  xmlSchemaSetParserStructuredErrors(
    ctx,
    Nokogiri_error_array_pusher,
    (void *)errors
  );
#endif

  if (parse_options_int & XML_PARSE_NONET) {
    old_loader = xmlGetExternalEntityLoader();
    xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader);
  }

  schema = xmlSchemaParse(ctx);

  if (old_loader) {
    xmlSetExternalEntityLoader(old_loader);
  }

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlSchemaFreeParserCtxt(ctx);

  if (NULL == schema) {
    xmlErrorPtr error = xmlGetLastError();
    if (error) {
      Nokogiri_error_raise(NULL, error);
    } else {
      rb_raise(rb_eRuntimeError, "Could not parse document");
    }

    return Qnil;
  }

  rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema);
  rb_iv_set(rb_schema, "@errors", errors);
  rb_iv_set(rb_schema, "@parse_options", parse_options);

  return rb_schema;
}
```
  Create a new [`Schema`](schema) from the contents of `string`

      ### Public Instance Methods

     valid?(thing) Show source   
 
```
# File lib/nokogiri/xml/schema.rb, line 68
def valid?(thing)
  validate(thing).empty?
end
```
  Returns true if `thing` is a valid [`Nokogiri::XML::Document`](document) or file.

      validate(thing) Show source   
 
```
# File lib/nokogiri/xml/schema.rb, line 55
def validate(thing)
  if thing.is_a?(Nokogiri::XML::Document)
    validate_document(thing)
  elsif File.file?(thing)
    validate_file(thing)
  else
    raise ArgumentError, "Must provide Nokogiri::Xml::Document or the name of an existing file"
  end
end
```
  Validate `thing` against this schema. `thing` can be a [`Nokogiri::XML::Document`](document) object, or a filename. An Array of [`Nokogiri::XML::SyntaxError`](syntaxerror) objects found while validating the `thing` is returned.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Schema.html>

module Nokogiri::XML::Searchable
=================================

  The [`Searchable`](searchable) module declares the interface used for searching your DOM.

 It implements the public methods [`#search`](searchable#method-i-search), [`#css`](searchable#method-i-css), and [`#xpath`](searchable#method-i-xpath), as well as allowing specific implementations to specialize some of the important behaviors.

     ### Constants

   LOOKS\_LIKE\_XPATH   Regular expression used by [`Searchable#search`](searchable#method-i-search) to determine if a query string is [`CSS`](../css) or [`XPath`](xpath)

        Searching via XPath or CSS Queries
-----------------------------------

  [↑ top](#top)     ### Public Instance Methods

     %(\*args)    Alias for: [at](searchable#method-i-at)      /(\*args)    Alias for: [search](searchable#method-i-search)       >(selector) → NodeSet  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 196
def >(selector) # rubocop:disable Naming/BinaryOperatorParameterName
  ns = (document.root&.namespaces || {})
  xpath(CSS.xpath_for(selector, prefix: "./", ns: ns).first)
end
```
  Search this node’s immediate children using [`CSS`](../css) selector `selector`

       at(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 71
def at(*args)
  search(*args).first
end
```
  Search this object for `paths`, and return only the first result. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries.

 See [`Searchable#search`](searchable#method-i-search) for more information.

   Also aliased as: [%](searchable#method-i-25)       at\_css(\*rules, [namespace-bindings, custom-pseudo-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 140
def at_css(*args)
  css(*args).first
end
```
  Search this object for [`CSS`](../css) `rules`, and return only the first match. `rules` must be one or more [`CSS`](../css) selectors.

 See [`Searchable#css`](searchable#method-i-css) for more information.

       at\_xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 188
def at_xpath(*args)
  xpath(*args).first
end
```
  Search this node for [`XPath`](xpath) `paths`, and return only the first match. `paths` must be one or more [`XPath`](xpath) queries.

 See [`Searchable#xpath`](searchable#method-i-xpath) for more information.

       css(\*rules, [namespace-bindings, custom-pseudo-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 126
def css(*args)
  rules, handler, ns, _ = extract_params(args)

  css_internal(self, rules, handler, ns)
end
```
  Search this object for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example:

 
```
node.css('title')
node.css('body h1.bold')
node.css('div + p.green', 'div#one')

```
 A hash of namespace bindings may be appended. For example:

 
```
node.css('bike|tire', {'bike' => 'http://schwinn.com/'})

```
 💡 Custom [`CSS`](../css) pseudo classes may also be defined which are mapped to a custom [`XPath`](xpath) function. To define custom pseudo classes, create a class and implement the custom pseudo class you want defined. The first argument to the method will be the matching context [`NodeSet`](nodeset). Any other arguments are ones that you pass in. For example:

 
```
handler = Class.new {
  def regex(node_set, regex)
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.css('title:regex("\w+")', handler)

```
 💡 Some [`XPath`](xpath) syntax is supported in [`CSS`](../css) queries. For example, to query for an attribute:

 
```
node.css('img > @href') # returns all +href+ attributes on an +img+ element
node.css('img / @href') # same

# ⚠ this returns +class+ attributes from all +div+ elements AND THEIR CHILDREN!
node.css('div @class')

node.css

```
 💡 Array-like syntax is supported in [`CSS`](../css) queries as an alternative to using +:nth-child()+.

 ⚠ NOTE that indices are 1-based like `:nth-child` and not 0-based like Ruby Arrays. For example:

 
```
# equivalent to 'li:nth-child(2)'
node.css('li[2]') # retrieve the second li element in a list

```
 ⚠ NOTE that the [`CSS`](../css) query string is case-sensitive with regards to your document type. [`HTML`](../html4) tags will match only lowercase [`CSS`](../css) queries, so if you search for “H1” in an [`HTML`](../html4) document, you’ll never find anything. However, “H1” might be found in an [`XML`](../xml) document, where tags names are case-sensitive (e.g., “H1” is distinct from “h1”).

       search(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 51
def search(*args)
  paths, handler, ns, binds = extract_params(args)

  xpaths = paths.map(&:to_s).map do |path|
    LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns)
  end.flatten.uniq

  xpath(*(xpaths + [ns, handler, binds].compact))
end
```
  Search this object for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries:

 
```
node.search("div.employee", ".//title")

```
 A hash of namespace bindings may be appended:

 
```
node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'})
node.search('bike|tire', {'bike' => 'http://schwinn.com/'})

```
 For [`XPath`](xpath) queries, a hash of variable bindings may also be appended to the namespace bindings. For example:

 
```
node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'})

```
 💡 Custom [`XPath`](xpath) functions and [`CSS`](../css) pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

 
```
handler = Class.new {
  def regex node_set, regex
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler)

```
 See [`Searchable#xpath`](searchable#method-i-xpath) and [`Searchable#css`](searchable#method-i-css) for further usage help.

   Also aliased as: [/](searchable#method-i-2F)       xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class])  Show source   
 
```
# File lib/nokogiri/xml/searchable.rb, line 174
def xpath(*args)
  paths, handler, ns, binds = extract_params(args)

  xpath_internal(self, paths, handler, ns, binds)
end
```
  Search this node for [`XPath`](xpath) `paths`. `paths` must be one or more [`XPath`](xpath) queries.

 
```
node.xpath('.//title')

```
 A hash of namespace bindings may be appended. For example:

 
```
node.xpath('.//foo:name', {'foo' => 'http://example.org/'})
node.xpath('.//xmlns:name', node.root.namespaces)

```
 A hash of variable bindings may also be appended to the namespace bindings. For example:

 
```
node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'})

```
 💡 Custom [`XPath`](xpath) functions may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

 
```
handler = Class.new {
  def regex(node_set, regex)
    node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
  end
}.new
node.xpath('.//title[regex(., "\w+")]', handler)

```
    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Searchable.html>

class Nokogiri::XML::SyntaxError
=================================



Parent:
cNokogiriSyntaxError
  The [`XML::SyntaxError`](syntaxerror) is raised on parse errors

 This class provides information about [`XML`](../xml) SyntaxErrors. These exceptions are typically stored on [`Nokogiri::XML::Document#errors`](document#attribute-i-errors).

     ### Attributes

    code[R]     column[R]     domain[R]     file[R]     int1[R]     level[R]     line[R]     str1[R]     str2[R]     str3[R]      ### Public Instance Methods

     error?() Show source   
 
```
# File lib/nokogiri/xml/syntax_error.rb, line 34
def error?
  level == 2
end
```
  return true if this is an error

      fatal?() Show source   
 
```
# File lib/nokogiri/xml/syntax_error.rb, line 40
def fatal?
  level == 3
end
```
  return true if this error is fatal

      none?() Show source   
 
```
# File lib/nokogiri/xml/syntax_error.rb, line 22
def none?
  level == 0
end
```
  return true if this is a non error

      to\_s() Show source   
 
```
# File lib/nokogiri/xml/syntax_error.rb, line 44
def to_s
  message = super.chomp
  [location_to_s, level_to_s, message]
    .compact.join(": ")
    .force_encoding(message.encoding)
end
```
   Calls superclass method       warning?() Show source   
 
```
# File lib/nokogiri/xml/syntax_error.rb, line 28
def warning?
  level == 1
end
```
  return true if this is a warning

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/SyntaxError.html>

class Nokogiri::XML::Text
==========================



Parent:
cNokogiriXmlCharacterData
  Wraps [`Text`](text) nodes.

     ### Public Class Methods

      new(content, document)  Show source   
 
```
static VALUE
new (int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr doc;
  xmlNodePtr node;
  VALUE string;
  VALUE document;
  VALUE rest;
  VALUE rb_node;

  rb_scan_args(argc, argv, "2*", &string, &document, &rest);

  Noko_Node_Get_Struct(document, xmlDoc, doc);

  node = xmlNewText((xmlChar *)StringValueCStr(string));
  node->doc = doc->doc;

  noko_xml_document_pin_node(node);

  rb_node = noko_xml_node_wrap(klass, node) ;
  rb_obj_call_init(rb_node, argc, argv);

  if (rb_block_given_p()) { rb_yield(rb_node); }

  return rb_node;
}
```
  Create a new [`Text`](text) element on the `document` with `content`

      ### Public Instance Methods

     content=(string) Show source   
 
```
# File lib/nokogiri/xml/text.rb, line 6
def content=(string)
  self.native_content = string.to_s
end
```
     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/Text.html>

module Nokogiri::XML::XPath
============================

    ### Constants

   CURRENT\_SEARCH\_PREFIX   The [`XPath`](xpath) search prefix to search direct descendants of the current element, `./`

  GLOBAL\_SEARCH\_PREFIX   The [`XPath`](xpath) search prefix to search globally, `//`

  ROOT\_SEARCH\_PREFIX   The [`XPath`](xpath) search prefix to search direct descendants of the root element, `/`

  SUBTREE\_SEARCH\_PREFIX   The [`XPath`](xpath) search prefix to search anywhere in the current element’s subtree, `.//`

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/XPath.html>

class Nokogiri::XML::XPath::SyntaxError
========================================



Parent:
cNokogiriXmlSyntaxError
    ### Public Instance Methods

     to\_s() Show source   
 
```
# File lib/nokogiri/xml/xpath/syntax_error.rb, line 7
def to_s
  [super.chomp, str1].compact.join(": ")
end
```
   Calls superclass method     

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/XPath/SyntaxError.html>

class Nokogiri::XML::XPathContext
==================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  [`XPathContext`](xpathcontext) is the entry point for searching a [`Document`](document) by using [`XPath`](xpath).

     ### Public Class Methods

      new(node)  Show source   
 
```
static VALUE
rb_xml_xpath_context_new(VALUE klass, VALUE nodeobj)
{
  xmlNodePtr node;
  xmlXPathContextPtr ctx;
  VALUE self;

  Noko_Node_Get_Struct(nodeobj, xmlNode, node);

#if LIBXML_VERSION < 21000
  /* deprecated in 40483d0 */
  xmlXPathInit();
#endif

  ctx = xmlXPathNewContext(node->doc);
  ctx->node = node;

  xmlXPathRegisterNs(ctx, NOKOGIRI_PREFIX, NOKOGIRI_URI);
  xmlXPathRegisterNs(ctx, NOKOGIRI_BUILTIN_PREFIX, NOKOGIRI_BUILTIN_URI);
  xmlXPathRegisterFuncNS(ctx, (const xmlChar *)"css-class", NOKOGIRI_BUILTIN_URI,
                         xpath_builtin_css_class);
  xmlXPathRegisterFuncNS(ctx, (const xmlChar *)"local-name-is", NOKOGIRI_BUILTIN_URI,
                         xpath_builtin_local_name_is);

  self = Data_Wrap_Struct(klass, 0, xml_xpath_context_deallocate, ctx);
  return self;
}
```
  Create a new [`XPathContext`](xpathcontext) with `node` as the reference point.

      ### Public Instance Methods

      evaluate(search\_path, handler = nil)  Show source   
 
```
static VALUE
rb_xml_xpath_context_evaluate(int argc, VALUE *argv, VALUE self)
{
  VALUE search_path, xpath_handler;
  VALUE retval = Qnil;
  xmlXPathContextPtr ctx;
  xmlXPathObjectPtr xpath;
  xmlChar *query;
  VALUE errors = rb_ary_new();

  Data_Get_Struct(self, xmlXPathContext, ctx);

  if (rb_scan_args(argc, argv, "11", &search_path, &xpath_handler) == 1) {
    xpath_handler = Qnil;
  }

  query = (xmlChar *)StringValueCStr(search_path);

  if (Qnil != xpath_handler) {
    /* FIXME: not sure if this is the correct place to shove private data. */
    ctx->userData = (void *)xpath_handler;
    xmlXPathRegisterFuncLookup(ctx, handler_lookup, (void *)xpath_handler);
  }

  xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher);
  xmlSetGenericErrorFunc((void *)errors, generic_exception_pusher);

  xpath = xmlXPathEvalExpression(query, ctx);

  xmlSetStructuredErrorFunc(NULL, NULL);
  xmlSetGenericErrorFunc(NULL, NULL);

  if (xpath == NULL) {
    rb_exc_raise(rb_ary_entry(errors, 0));
  }

  retval = xpath2ruby(xpath, ctx);
  if (retval == Qundef) {
    retval = noko_xml_node_set_wrap(NULL, DOC_RUBY_OBJECT(ctx->doc));
  }

  xmlXPathFreeNodeSetList(xpath);

  return retval;
}
```
  Evaluate the `search_path` returning an [`XML::XPath`](xpath) object.

      register\_namespaces(namespaces) Show source   
 
```
# File lib/nokogiri/xml/xpath_context.rb, line 8
def register_namespaces(namespaces)
  namespaces.each do |k, v|
    k = k.to_s.gsub(/.*:/, "") # strip off 'xmlns:' or 'xml:'
    register_ns(k, v)
  end
end
```
  Register namespaces in `namespaces`

       register\_ns(prefix, uri)  Show source   
 
```
static VALUE
rb_xml_xpath_context_register_ns(VALUE self, VALUE prefix, VALUE uri)
{
  xmlXPathContextPtr ctx;
  Data_Get_Struct(self, xmlXPathContext, ctx);

  xmlXPathRegisterNs(ctx,
                     (const xmlChar *)StringValueCStr(prefix),
                     (const xmlChar *)StringValueCStr(uri)
                    );
  return self;
}
```
  Register the namespace with `prefix` and `uri`.

       register\_variable(name, value)  Show source   
 
```
static VALUE
rb_xml_xpath_context_register_variable(VALUE self, VALUE name, VALUE value)
{
  xmlXPathContextPtr ctx;
  xmlXPathObjectPtr xmlValue;
  Data_Get_Struct(self, xmlXPathContext, ctx);

  xmlValue = xmlXPathNewCString(StringValueCStr(value));

  xmlXPathRegisterVariable(ctx,
                           (const xmlChar *)StringValueCStr(name),
                           xmlValue
                          );

  return self;
}
```
  Register the variable `name` with `value`.

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/XPathContext.html>

module Nokogiri::XSLT
======================

  See [`Nokogiri::XSLT::Stylesheet`](xslt/stylesheet) for creating and manipulating [`Stylesheet`](xslt/stylesheet) object.

     ### Public Class Methods

     parse(string, modules = {}) Show source   
 
```
# File lib/nokogiri/xslt.rb, line 25
def parse(string, modules = {})
  modules.each do |url, klass|
    XSLT.register(url, klass)
  end

  doc = XML::Document.parse(string, nil, nil, XML::ParseOptions::DEFAULT_XSLT)
  if Nokogiri.jruby?
    Stylesheet.parse_stylesheet_doc(doc, string)
  else
    Stylesheet.parse_stylesheet_doc(doc)
  end
end
```
  Parse the stylesheet in `string`, register any `modules`

       quote\_params(params) → Array  Show source   
 
```
# File lib/nokogiri/xslt.rb, line 49
def quote_params(params)
  params.flatten.each_slice(2).with_object([]) do |kv, quoted_params|
    key, value = kv.map(&:to_s)
    value = if /'/.match?(value)
      "concat('#{value.gsub(/'/, %q{', "'", '})}')"
    else
      "'#{value}'"
    end
    quoted_params << key
    quoted_params << value
  end
end
```
  Quote parameters in `params` for stylesheet safety. See [`Nokogiri::XSLT::Stylesheet.transform`](xslt/stylesheet#method-i-transform) for example usage.

  Parameters   * `params` (Hash, Array) [`XSLT`](xslt) parameters (key->value, or tuples of [key, value])

  Returns   Array of string parameters, with quotes correctly escaped for use with [`XSLT::Stylesheet.transform`](xslt/stylesheet#method-i-transform)

      

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XSLT.html>

class Nokogiri::XSLT::Stylesheet
=================================



Parent:
[Object](https://nokogiri.org/rdoc/Object.html)
  A [`Stylesheet`](stylesheet) represents an [`XSLT`](../xslt) [`Stylesheet`](stylesheet) object. [`Stylesheet`](stylesheet) creation is done through [`Nokogiri.XSLT`](../../nokogiri#method-c-XSLT). Here is an example of transforming an [`XML::Document`](../xml/document) with a Stylesheet:

 
```
doc   = Nokogiri::XML(File.read('some_file.xml'))
xslt  = Nokogiri::XSLT(File.read('some_transformer.xslt'))

puts xslt.transform(doc)

```
 See [`Nokogiri::XSLT::Stylesheet#transform`](stylesheet#method-i-transform) for more transformation information.

     ### Public Class Methods

      parse\_stylesheet\_doc(document)  Show source   
 
```
static VALUE
parse_stylesheet_doc(VALUE klass, VALUE xmldocobj)
{
  xmlDocPtr xml, xml_cpy;
  VALUE errstr, exception;
  xsltStylesheetPtr ss ;
  Data_Get_Struct(xmldocobj, xmlDoc, xml);

  errstr = rb_str_new(0, 0);
  xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler);

  xml_cpy = xmlCopyDoc(xml, 1); /* 1 => recursive */
  ss = xsltParseStylesheetDoc(xml_cpy);

  xsltSetGenericErrorFunc(NULL, NULL);

  if (!ss) {
    xmlFreeDoc(xml_cpy);
    exception = rb_exc_new3(rb_eRuntimeError, errstr);
    rb_exc_raise(exception);
  }

  return Nokogiri_wrap_xslt_stylesheet(ss);
}
```
  Parse a stylesheet from `document`.

      ### Public Instance Methods

     apply\_to(document, params = []) Show source   
 
```
# File lib/nokogiri/xslt/stylesheet.rb, line 22
def apply_to(document, params = [])
  serialize(transform(document, params))
end
```
  Apply an [`XSLT`](../xslt) stylesheet to an [`XML::Document`](../xml/document). `params` is an array of strings used as [`XSLT`](../xslt) parameters. returns serialized document

       serialize(document)  Show source   
 
```
static VALUE
serialize(VALUE self, VALUE xmlobj)
{
  xmlDocPtr xml ;
  nokogiriXsltStylesheetTuple *wrapper;
  xmlChar *doc_ptr ;
  int doc_len ;
  VALUE rval ;

  Data_Get_Struct(xmlobj, xmlDoc, xml);
  Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper);
  xsltSaveResultToString(&doc_ptr, &doc_len, xml, wrapper->ss);
  rval = NOKOGIRI_STR_NEW(doc_ptr, doc_len);
  xmlFree(doc_ptr);
  return rval ;
}
```
  Serialize `document` to an xml string.

       transform(document)  Show source    transform(document, params = {})    
 
```
static VALUE
transform(int argc, VALUE *argv, VALUE self)
{
  VALUE xmldoc, paramobj, errstr, exception ;
  xmlDocPtr xml ;
  xmlDocPtr result ;
  nokogiriXsltStylesheetTuple *wrapper;
  const char **params ;
  long param_len, j ;
  int parse_error_occurred ;

  rb_scan_args(argc, argv, "11", &xmldoc, &paramobj);
  if (NIL_P(paramobj)) { paramobj = rb_ary_new2(0L) ; }
  if (!rb_obj_is_kind_of(xmldoc, cNokogiriXmlDocument)) {
    rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::Document");
  }

  /* handle hashes as arguments. */
  if (T_HASH == TYPE(paramobj)) {
    paramobj = rb_funcall(paramobj, rb_intern("to_a"), 0);
    paramobj = rb_funcall(paramobj, rb_intern("flatten"), 0);
  }

  Check_Type(paramobj, T_ARRAY);

  Data_Get_Struct(xmldoc, xmlDoc, xml);
  Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper);

  param_len = RARRAY_LEN(paramobj);
  params = ruby_xcalloc((size_t)param_len + 1, sizeof(char *));
  for (j = 0 ; j < param_len ; j++) {
    VALUE entry = rb_ary_entry(paramobj, j);
    const char *ptr = StringValueCStr(entry);
    params[j] = ptr;
  }
  params[param_len] = 0 ;

  errstr = rb_str_new(0, 0);
  xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler);
  xmlSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler);

  result = xsltApplyStylesheet(wrapper->ss, xml, params);
  ruby_xfree(params);

  xsltSetGenericErrorFunc(NULL, NULL);
  xmlSetGenericErrorFunc(NULL, NULL);

  parse_error_occurred = (Qfalse == rb_funcall(errstr, rb_intern("empty?"), 0));

  if (parse_error_occurred) {
    exception = rb_exc_new3(rb_eRuntimeError, errstr);
    rb_exc_raise(exception);
  }

  return noko_xml_document_wrap((VALUE)0, result) ;
}
```
  Apply an [`XSLT`](../xslt) stylesheet to an [`XML::Document`](../xml/document).

  Parameters   * `document` ([`Nokogiri::XML::Document`](../xml/document)) the document to be transformed.
* `params` (Hash, Array) strings used as [`XSLT`](../xslt) parameters.

  Returns   [`Nokogiri::XML::Document`](../xml/document)

   **Example** of basic transformation:

 
```
xslt = <<~XSLT
  <xsl:stylesheet version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:param name="title"/>

  <xsl:template match="/">
    <html>
      <body>
        <h1><xsl:value-of select="$title"/></h1>
        <ol>
          <xsl:for-each select="staff/employee">
            <li><xsl:value-of select="employeeId"></li>
          </xsl:for-each>
        </ol>
      </body>
    </html>
  </xsl:stylesheet>
XSLT

xml = <<~XML
  <?xml version="1.0"?>
  <staff>
    <employee>
      <employeeId>EMP0001</employeeId>
      <position>Accountant</position>
    </employee>
    <employee>
      <employeeId>EMP0002</employeeId>
      <position>Developer</position>
    </employee>
  </staff>
XML

doc = Nokogiri::XML::Document.parse(xml)
stylesheet = Nokogiri::XSLT.parse(xslt)

```
 ⚠ Note that the `h1` element is empty because no param has been provided!

 
```
stylesheet.transform(doc).to_xml
# => "<html><body>\n" +
#    "<h1></h1>\n" +
#    "<ol>\n" +
#    "<li>EMP0001</li>\n" +
#    "<li>EMP0002</li>\n" +
#    "</ol>\n" +
#    "</body></html>\n"

```
 **Example** of using an input parameter hash:

 ⚠ The title is populated, but note how we need to quote-escape the value.

 
```
stylesheet.transform(doc, { "title" => "'Employee List'" }).to_xml
# => "<html><body>\n" +
#    "<h1>Employee List</h1>\n" +
#    "<ol>\n" +
#    "<li>EMP0001</li>\n" +
#    "<li>EMP0002</li>\n" +
#    "</ol>\n" +
#    "</body></html>\n"

```
 **Example** using the [`XSLT.quote_params`](../xslt#method-c-quote_params) helper method to safely quote-escape strings:

 
```
stylesheet.transform(doc, Nokogiri::XSLT.quote_params({ "title" => "Aaron's List" })).to_xml
# => "<html><body>\n" +
#    "<h1>Aaron's List</h1>\n" +
#    "<ol>\n" +
#    "<li>EMP0001</li>\n" +
#    "<li>EMP0002</li>\n" +
#    "</ol>\n" +
#    "</body></html>\n"

```
 **Example** using an array of [`XSLT`](../xslt) parameters

 You can also use an array if you want to.

 
```
stylesheet.transform(doc, ["title", "'Employee List'"]).to_xml
# => "<html><body>\n" +
#    "<h1>Employee List</h1>\n" +
#    "<ol>\n" +
#    "<li>EMP0001</li>\n" +
#    "<li>EMP0002</li>\n" +
#    "</ol>\n" +
#    "</body></html>\n"

```
 Or pass an array to [`XSLT.quote_params`](../xslt#method-c-quote_params):

 
```
stylesheet.transform(doc, Nokogiri::XSLT.quote_params(["title", "Aaron's List"])).to_xml
# => "<html><body>\n" +
#    "<h1>Aaron's List</h1>\n" +
#    "<ol>\n" +
#    "<li>EMP0001</li>\n" +
#    "<li>EMP0002</li>\n" +
#    "</ol>\n" +
#    "</body></html>\n"

```
 See: [`Nokogiri::XSLT.quote_params`](../xslt#method-c-quote_params)

    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XSLT/Stylesheet.html>

module XSD
===========

 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/XSD.html>

module XSD::XMLParser
======================

 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/XSD/XMLParser.html>

module Nokogiri::XML::PP::Node
===============================

 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/PP/Node.html>

class XSD::XMLParser::Nokogiri
===============================



Parent:
XSD::XMLParser::Parser
  [`Nokogiri`](nokogiri) XML parser for soap4r.

 [`Nokogiri`](nokogiri) may be used as the XML parser in soap4r. Simply require ‘xsd/xmlparser/nokogiri’ in your soap4r applications, and soap4r will use [`Nokogiri`](nokogiri) as it’s XML parser. No other changes should be required to use [`Nokogiri`](nokogiri) as the XML parser.

 Example (using UW ITS Web Services):

 
```
require 'rubygems'
require 'nokogiri'
gem 'soap4r'
require 'defaultDriver'
require 'xsd/xmlparser/nokogiri'

obj = AvlPortType.new
obj.getLatestByRoute(obj.getAgencies.first, 8).each do |bus|
  p "#{bus.routeID}, #{bus.longitude}, #{bus.latitude}"
end

```
     ### Public Class Methods

     new(host, opt = {}) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 31
def initialize(host, opt = {})
  super
  @parser = ::Nokogiri::XML::SAX::Parser.new(self, @charset || "UTF-8")
end
```
  Create a new [`XSD`](../../xsd) parser with `host` and `opt`

  Calls superclass method       ### Public Instance Methods

     cdata\_block(string) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 63
def cdata_block(string)
  characters(string)
end
```
  Handle cdata\_blocks containing `string`

      do\_parse(string\_or\_readable) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 38
def do_parse(string_or_readable)
  @parser.parse(string_or_readable)
end
```
  Start parsing `string_or_readable`

      end\_element(name) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 50
def end_element(name)
  super
end
```
  Handle the [`end_element`](nokogiri#method-i-end_element) event with `name`

  Calls superclass method       end\_element\_namespace(name, prefix = nil, uri = nil) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 91
def end_element_namespace(name, prefix = nil, uri = nil)
  ###
  # Deal with SAX v1 interface
  end_element([prefix, name].compact.join(":"))
end
```
  Called at the end of an element `name` is the element’s name `prefix` is the namespace prefix associated with the element `uri` is the associated namespace URI

      error(msg) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 56
def error(msg)
  raise ParseError, msg
end
```
  Handle errors with message `msg`

   Also aliased as: [warning](nokogiri#method-i-warning)      start\_element(name, attrs = []) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 44
def start_element(name, attrs = [])
  super(name, Hash[*attrs.flatten])
end
```
  Handle the [`start_element`](nokogiri#method-i-start_element) event with `name` and `attrs`

  Calls superclass method       start\_element\_namespace(name, attrs = [], prefix = nil, uri = nil, ns = []) Show source   
 
```
# File lib/xsd/xmlparser/nokogiri.rb, line 74
def start_element_namespace(name, attrs = [], prefix = nil, uri = nil, ns = [])
  ###
  # Deal with SAX v1 interface
  name = [prefix, name].compact.join(":")
  attributes = ns.map do |ns_prefix, ns_uri|
    [["xmlns", ns_prefix].compact.join(":"), ns_uri]
  end + attrs.map do |attr|
    [[attr.prefix, attr.localname].compact.join(":"), attr.value]
  end.flatten
  start_element(name, attributes)
end
```
  Called at the beginning of an element `name` is the element name `attrs` is a list of attributes `prefix` is the namespace prefix for the element `uri` is the associated namespace URI `ns` is a hash of namespace prefix:urls associated with the element

      warning(msg)    Alias for: [error](nokogiri#method-i-error)    

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/XSD/XMLParser/Nokogiri.html>

module Nokogiri::XML::PP::CharacterData
========================================

 

 © 2008–2023 by Mike Dalessio, Aaron Patterson, Yoko Harada, Akinori MUSHA, John Shahid,  
Karol Bucek, Sam Ruby, Craig Barnes, Stephen Checkoway, Lars Kanis, Sergio Arbeo,  
Timothy Elliott, Nobuyoshi Nakada, Charles Nutter, Patrick MahoneyLicensed under the MIT License.  

<https://nokogiri.org/rdoc/Nokogiri/XML/PP/CharacterData.html>

nokogiri