Parent

Nokogiri::XML::Node

Nokogiri::XML::Node is your window to the fun filled world of dealing with XML and HTML tags. A Nokogiri::XML::Node may be treated similarly to a hash with regard to attributes. For example (from irb):

  irb(main):004:0> node
  => <a href="#foo" id="link">link</a>
  irb(main):005:0> node['href']
  => "#foo"
  irb(main):006:0> node.keys
  => ["href", "id"]
  irb(main):007:0> node.values
  => ["#foo", "link"]
  irb(main):008:0> node['class'] = 'green'
  => "green"
  irb(main):009:0> node
  => <a href="#foo" id="link" class="green">link</a>
  irb(main):010:0>

See Nokogiri::XML::Node#[] and Nokogiri::XML#[]= for more information.

Nokogiri::XML::Node also has methods that let you move around your tree. For navigating your tree, see:

You may search this node’s subtree using Node#xpath and Node#css

Constants

ELEMENT_NODE

Element node type, see Nokogiri::XML::Node#element?

ATTRIBUTE_NODE

Attribute node type

TEXT_NODE

Text node type, see Nokogiri::XML::Node#text?

CDATA_SECTION_NODE

CDATA node type, see Nokogiri::XML::Node#cdata?

ENTITY_REF_NODE

Entity reference node type

ENTITY_NODE

Entity node type

PI_NODE

PI node type

COMMENT_NODE

Comment node type, see Nokogiri::XML::Node#comment?

DOCUMENT_NODE

Document node type, see Nokogiri::XML::Node#xml?

DOCUMENT_TYPE_NODE

Document type node type

DOCUMENT_FRAG_NODE

Document fragment node type

NOTATION_NODE

Notation node type

HTML_DOCUMENT_NODE

HTML document node type, see Nokogiri::XML::Node#html?

DTD_NODE

DTD node type

ELEMENT_DECL

Element declaration type

ATTRIBUTE_DECL

Attribute declaration type

ENTITY_DECL

Entity declaration type

NAMESPACE_DECL

Namespace declaration type

XINCLUDE_START

XInclude start type

XINCLUDE_END

XInclude end type

DOCB_DOCUMENT_NODE

DOCB document node type

Public Class Methods

new(name, document) click to toggle source

Create a new node with name sharing GC lifecycle with document

static VALUE new(int argc, VALUE *argv, VALUE klass)
{
  xmlDocPtr doc;
  VALUE name;
  VALUE document;
  VALUE rest;

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

  Data_Get_Struct(document, xmlDoc, doc);

  xmlNodePtr node = xmlNewNode(NULL, (xmlChar *)StringValuePtr(name));
  node->doc = doc->doc;
  NOKOGIRI_ROOT_NODE(node);

  VALUE rb_node = Nokogiri_wrap_xml_node(klass, node);
  rb_funcall2(rb_node, rb_intern("initialize"), argc, argv);

  if(rb_block_given_p()) rb_yield(rb_node);

  return rb_node;
}
new(name, document) click to toggle source

(Not documented)

# File lib/nokogiri/xml/node.rb, line 80
      def initialize name, document
        # ... Ya.  This is empty on purpose.
      end

Public Instance Methods

%(path, ns = document.root ? document.root.namespaces : {}) click to toggle source

Alias for at

/(*paths) click to toggle source

Alias for search

<<(p1) click to toggle source

Alias for add_child

<=>(other) click to toggle source

Compare two Node objects with respect to their Document. Nodes from different documents cannot be compared.

# File lib/nokogiri/xml/node.rb, line 636
      def <=> other
        return nil unless other.is_a?(Nokogiri::XML::Node)
        return nil unless document == other.document
        compare other
      end
==(other) click to toggle source

Test to see if this Node is equal to other

# File lib/nokogiri/xml/node.rb, line 478
      def == other
        return false unless other
        return false unless other.respond_to?(:pointer_id)
        pointer_id == other.pointer_id
      end
[](name) click to toggle source

Get the attribute value for the attribute name

# File lib/nokogiri/xml/node.rb, line 203
      def [] name
        return nil unless key?(name.to_s)
        get(name.to_s)
      end
Also aliased as: get_attribute
[]=(property, value) click to toggle source

Set the property to value

static VALUE set(VALUE self, VALUE property, VALUE value)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);

  xmlSetProp(node, (xmlChar *)StringValuePtr(property),
      (xmlChar *)StringValuePtr(value));

  return value;
}
accept(visitor) click to toggle source

Accept a visitor. This method calls “visit” on visitor with self.

# File lib/nokogiri/xml/node.rb, line 459
      def accept visitor
        visitor.visit(self)
      end
add_child(node) click to toggle source

Add node as a child of this node. Returns the new child node.

static VALUE add_child(VALUE self, VALUE child)
{
  return reparent_node_with(child, self, xmlAddChild);
}
Also aliased as: <<
add_namespace(p1, p2) click to toggle source
add_namespace_definition(prefix, href) click to toggle source

Adds a namespace definition with prefix using href

static VALUE add_namespace_definition(VALUE self, VALUE prefix, VALUE href)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);


  xmlNsPtr ns = xmlNewNs(
      node,
      (const xmlChar *)StringValuePtr(href),
      (const xmlChar *)(prefix == Qnil ? NULL : StringValuePtr(prefix))
  );

  if(!ns) {
    ns = xmlSearchNs(
        node->doc,
        node,
        (const xmlChar *)(prefix == Qnil ? NULL : StringValuePtr(prefix))
    );
  }

  if(Qnil == prefix) xmlSetNs(node, ns);

  return Nokogiri_wrap_xml_namespace(node->doc, ns);
}
Also aliased as: add_namespace
add_next_sibling(node) click to toggle source

Insert node after this node (as a sibling).

static VALUE add_next_sibling(VALUE self, VALUE rb_node)
{
  return reparent_node_with(rb_node, self, xmlAddNextSibling) ;
}
add_previous_sibling(node) click to toggle source

Insert node before this node (as a sibling).

static VALUE add_previous_sibling(VALUE self, VALUE rb_node)
{
  return reparent_node_with(rb_node, self, xmlAddPrevSibling) ;
}
after(data) click to toggle source

Create nodes from data and insert them after this node (as a sibling).

# File lib/nokogiri/xml/node.rb, line 278
      def after data
        fragment(data).children.to_a.reverse.each do |node|
          add_next_sibling node
        end
        self
      end
ancestors(selector = nil) click to toggle source

Get a list of ancestor Node for this Node. If selector is given, the ancestors must match selector

# File lib/nokogiri/xml/node.rb, line 413
      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

        NodeSet.new(document, parents.find_all { |parent|
          parent.matches?(selector)
        })
      end
at(path, ns = document.root ? document.root.namespaces : {}) click to toggle source

Search for the first occurrence of path. Returns nil if nothing is found, otherwise a Node.

# File lib/nokogiri/xml/node.rb, line 196
      def at path, ns = document.root ? document.root.namespaces : {}
        search(path, ns).first
      end
Also aliased as: %
attribute(name) click to toggle source

Get the attribute node with name

static VALUE attr(VALUE self, VALUE name)
{
  xmlNodePtr node;
  xmlAttrPtr prop;
  Data_Get_Struct(self, xmlNode, node);
  prop = xmlHasProp(node, (xmlChar *)StringValuePtr(name));

  if(! prop) return Qnil;
  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)prop);
}
attribute_nodes() click to toggle source

returns a list containing the Node attributes.

static VALUE attribute_nodes(VALUE self)
{
    /* this code in the mode of xmlHasProp() */
    xmlNodePtr node ;
    VALUE attr ;

    attr = rb_ary_new() ;
    Data_Get_Struct(self, xmlNode, node);

    Nokogiri_xml_node_properties(node, attr);

    return attr ;
}
attribute_with_ns(name, namespace) click to toggle source

Get the attribute node with name and namespace

static VALUE attribute_with_ns(VALUE self, VALUE name, VALUE namespace)
{
  xmlNodePtr node;
  xmlAttrPtr prop;
  Data_Get_Struct(self, xmlNode, node);
  prop = xmlHasNsProp(node, (xmlChar *)StringValuePtr(name),
      Qnil == namespace ? NULL : (xmlChar *)StringValuePtr(namespace));

  if(! prop) return Qnil;
  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)prop);
}
attributes() click to toggle source

Returns a hash containing the node’s attributes. The key is the attribute name, the value is the string value of the attribute.

# File lib/nokogiri/xml/node.rb, line 226
      def attributes
        Hash[*(attribute_nodes.map { |node|
          [node.node_name, node]
        }.flatten)]
      end
before(data) click to toggle source

Create nodes from data and insert them before this node (as a sibling).

# File lib/nokogiri/xml/node.rb, line 268
      def before data
        fragment(data).children.each do |node|
          add_previous_sibling node
        end
        self
      end
blank? click to toggle source

Is this node blank?

static VALUE blank_eh(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  if(1 == xmlIsBlankNode(node))
    return Qtrue;
  return Qfalse;
}
cdata?() click to toggle source

Returns true if this is a CDATA

# File lib/nokogiri/xml/node.rb, line 343
      def cdata?
        type == CDATA_SECTION_NODE
      end
child click to toggle source

Returns the child node

static VALUE child(VALUE self)
{
  xmlNodePtr node, child;
  Data_Get_Struct(self, xmlNode, node);

  child = node->children;
  if(!child) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, child);
}
children click to toggle source

Get the list of children for this node as a NodeSet

static VALUE children(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);

  xmlNodePtr child = node->children;
  xmlNodeSetPtr set = xmlXPathNodeSetCreate(child);

  if(!child) return Nokogiri_wrap_xml_node_set(set);

  child = child->next;
  while(NULL != child) {
    xmlXPathNodeSetAdd(set, child);
    child = child->next;
  }

  VALUE node_set = Nokogiri_wrap_xml_node_set(set);
  rb_iv_set(node_set, "@document", DOC_RUBY_OBJECT(node->doc));

  return node_set;
}
clone(...) click to toggle source

Alias for dup

collect_namespaces() click to toggle source

recursively get all namespaces from this node and its subtree

# File lib/nokogiri/xml/node.rb, line 403
      def collect_namespaces
        # TODO: print warning message if a prefix refers to more than one URI in the document?
        ns = {}
        traverse {|j| ns.merge!(j.namespaces)}
        ns
      end
comment?() click to toggle source

Returns true if this is a Comment

# File lib/nokogiri/xml/node.rb, line 338
      def comment?
        type == COMMENT_NODE
      end
content click to toggle source

Returns the content for this Node

static VALUE get_content(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);

  xmlChar * content = xmlNodeGetContent(node);
  if(content) {
    VALUE rval = NOKOGIRI_STR_NEW2(content, node->doc->encoding);
    xmlFree(content);
    return rval;
  }
  return Qnil;
}
Also aliased as: text, inner_text
content=(string) click to toggle source

Set the Node content to string. The content gets XML escaped.

# File lib/nokogiri/xml/node.rb, line 311
      def content= string
        self.native_content = encode_special_chars(string.to_s)
      end
css(*rules) click to toggle source

Search this node for CSS rules. rules must be one or more CSS selectors. For example:

  node.css('title')
  node.css('body h1.bold')
  node.css('div + p.green', 'div#one')

Custom CSS pseudo classes may also be defined. 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 current matching NodeSet. Any other arguments are ones that you pass in. For example:

  node.css('title:regex("\w+")', Class.new {
    def regex node_set, regex
      node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
    end
  }.new)
# File lib/nokogiri/xml/node.rb, line 177
      def css *rules
        # Pop off our custom function handler if it exists
        handler = ![
          Hash, String, Symbol
        ].include?(rules.last.class) ? rules.pop : nil

        ns = rules.last.is_a?(Hash) ? rules.pop :
          (document.root ? document.root.namespaces : {})

        rules = rules.map { |rule|
          CSS.xpath_for(rule, :prefix => ".//", :ns => ns)
        }.flatten.uniq + [ns, handler].compact

        xpath(*rules)
      end
css_path() click to toggle source

Get the path to this node as a CSS expression

# File lib/nokogiri/xml/node.rb, line 396
      def css_path
        path.split(/\//).map { |part|
          part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
        }.compact.join(' > ')
      end
decorate!() click to toggle source

Decorate this node with the decorators set up in this node’s Document

# File lib/nokogiri/xml/node.rb, line 86
      def decorate!
        document.decorate(self)
      end
default_namespace=(url) click to toggle source

Set the default namespace for this node to url

# File lib/nokogiri/xml/node.rb, line 433
      def default_namespace= url
        add_namespace_definition(nil, url)
      end
delete(name) click to toggle source

Alias for remove_attribute

description() click to toggle source

Fetch the Nokogiri::HTML::ElementDescription for this node. Returns nil on XML documents and on unknown tags.

# File lib/nokogiri/xml/node.rb, line 365
      def description
        return nil if document.xml?
        Nokogiri::HTML::ElementDescription[name]
      end
document() click to toggle source

(Not documented)

# File lib/nokogiri/ffi/xml/node.rb, line 299
      def document
        cstruct.document.ruby_doc
      end
document click to toggle source

Get the document for this Node

static VALUE document(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  return DOC_RUBY_OBJECT(node->doc);
}
dup click to toggle source

Copy this node. An optional depth may be passed in, but it defaults to a deep copy. 0 is a shallow copy, 1 is a deep copy.

static VALUE duplicate_node(int argc, VALUE *argv, VALUE self)
{
  VALUE level;

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

  xmlNodePtr node, dup;
  Data_Get_Struct(self, xmlNode, node);

  dup = xmlDocCopyNode(node, node->doc, NUM2INT(level));
  if(dup == NULL) return Qnil;

  return Nokogiri_wrap_xml_node(rb_obj_class(self), dup);
}
Also aliased as: clone
each(&block) click to toggle source

Iterate over each attribute name and value pair for this Node.

# File lib/nokogiri/xml/node.rb, line 246
      def each &block
        attribute_nodes.each { |node|
          block.call(node.node_name, node.value)
        }
      end
elem?() click to toggle source

Alias for element?

element?() click to toggle source

Returns true if this is an Element node

# File lib/nokogiri/xml/node.rb, line 378
      def element?
        type == ELEMENT_NODE
      end
Also aliased as: elem?
encode_special_chars(string) click to toggle source

Encode any special characters in string

static VALUE encode_special_chars(VALUE self, VALUE string)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  xmlChar * encoded = xmlEncodeSpecialChars(
      node->doc,
      (const xmlChar *)StringValuePtr(string)
  );

  VALUE encoded_str = NOKOGIRI_STR_NEW2(encoded, node->doc->encoding);
  xmlFree(encoded);

  return encoded_str;
}
get_attribute(name) click to toggle source

Alias for #[]

has_attribute?(p1) click to toggle source

Alias for key?

html?() click to toggle source

Returns true if this is an HTML::Document node

# File lib/nokogiri/xml/node.rb, line 353
      def html?
        type == HTML_DOCUMENT_NODE
      end
inner_html() click to toggle source

Get the inner_html for this node’s Node#children

# File lib/nokogiri/xml/node.rb, line 391
      def inner_html
        children.map { |x| x.to_html }.join
      end
inner_html=(tags) click to toggle source

Set the inner_html for this Node to tags

# File lib/nokogiri/xml/node.rb, line 295
      def inner_html= tags
        children.each { |x| x.remove}

        fragment(tags).children.to_a.reverse.each do |node|
          add_child node
        end
        self
      end
inner_text() click to toggle source

Alias for content

internal_subset click to toggle source

Get the internal subset

static VALUE internal_subset(VALUE self)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  Data_Get_Struct(self, xmlNode, node);

  if(!node->doc) return Qnil;

  doc = node->doc;
  xmlDtdPtr dtd = xmlGetIntSubset(doc);

  if(!dtd) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)dtd);
}
key?(attribute) click to toggle source

Returns true if attribute is set

static VALUE key_eh(VALUE self, VALUE attribute)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  if(xmlHasProp(node, (xmlChar *)StringValuePtr(attribute)))
    return Qtrue;
  return Qfalse;
}
Also aliased as: has_attribute?
keys() click to toggle source

Get the attribute names for this Node.

# File lib/nokogiri/xml/node.rb, line 240
      def keys
        attribute_nodes.map { |node| node.node_name }
      end
line click to toggle source

Returns the line for this Node

static VALUE line(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);

  return INT2NUM(node->line);
}
matches?(selector) click to toggle source

Returns true if this Node matches selector

# File lib/nokogiri/xml/node.rb, line 261
      def matches? selector
        document.search(selector).include?(self)
      end
name() click to toggle source

Alias for node_name

name=(p1) click to toggle source

Alias for node_name=

namespace() click to toggle source

returns the Nokogiri::XML::Namespace for the node, if one exists.

static VALUE namespace(VALUE self)
{
  xmlNodePtr node ;
  Data_Get_Struct(self, xmlNode, node);

  if (node->ns)
    return Nokogiri_wrap_xml_namespace(node->doc, node->ns);

  return Qnil ;
}
namespace=(ns) click to toggle source

Set the namespace for this node to ns

# File lib/nokogiri/xml/node.rb, line 440
      def namespace= ns
        if ns.document != document
          raise ArgumentError, 'namespace must be declared on the same document'
        end
        unless ns.is_a? Nokogiri::XML::Namespace
          raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
        end
        set_namespace ns
      end
namespace_definitions() click to toggle source

returns a list of Namespace nodes defined on self

static VALUE namespace_definitions(VALUE self)
{
  /* this code in the mode of xmlHasProp() */
  xmlNodePtr node ;

  Data_Get_Struct(self, xmlNode, node);

  VALUE list = rb_ary_new();

  xmlNsPtr ns = node->nsDef;

  if(!ns) return list;

  while(NULL != ns) {
    rb_ary_push(list, Nokogiri_wrap_xml_namespace(node->doc, ns));
    ns = ns->next;
  }

  return list;
}
namespaced_key?(attribute, namespace) click to toggle source

Returns true if attribute is set with namespace

static VALUE namespaced_key_eh(VALUE self, VALUE attribute, VALUE namespace)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  if(xmlHasNsProp(node, (xmlChar *)StringValuePtr(attribute),
        Qnil == namespace ? NULL : (xmlChar *)StringValuePtr(namespace)))
    return Qtrue;
  return Qfalse;
}
namespaces() click to toggle source

Get a hash containing the Namespace definitions for this Node

# File lib/nokogiri/xml/node.rb, line 324
      def namespaces
        Hash[*namespace_definitions.map { |nd|
          key = ['xmlns', nd.prefix].compact.join(':')
          if RUBY_VERSION >= '1.9' && document.encoding
            begin
              key.force_encoding document.encoding
            rescue ArgumentError
            end
          end
          [key, nd.href]
        }.flatten]
      end
next() click to toggle source

Alias for next_sibling

next_sibling click to toggle source

Returns the next sibling node

static VALUE next_sibling(VALUE self)
{
  xmlNodePtr node, sibling;
  Data_Get_Struct(self, xmlNode, node);

  sibling = node->next;
  if(!sibling) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, sibling) ;
}
Also aliased as: next
name click to toggle source

Returns the name for this Node

static VALUE get_name(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  if(node->name)
    return NOKOGIRI_STR_NEW2(node->name, node->doc->encoding);
  return Qnil;
}
Also aliased as: name
name=(new_name) click to toggle source

Set the name for this Node

static VALUE set_name(VALUE self, VALUE new_name)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  xmlNodeSetName(node, (xmlChar*)StringValuePtr(new_name));
  return new_name;
}
Also aliased as: name=
node_type click to toggle source

Get the type for this Node

static VALUE node_type(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  return INT2NUM((int)node->type);
}
Also aliased as: type
parent click to toggle source

Get the parent Node for this Node

static VALUE get_parent(VALUE self)
{
  xmlNodePtr node, parent;
  Data_Get_Struct(self, xmlNode, node);

  parent = node->parent;
  if(!parent) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, parent) ;
}
parent=(parent_node) click to toggle source

Set the parent Node for this Node

# File lib/nokogiri/xml/node.rb, line 317
      def parent= parent_node
        parent_node.add_child(self)
        parent_node
      end
path click to toggle source

Returns the path associated with this Node

static VALUE path(VALUE self)
{
  xmlNodePtr node;
  xmlChar *path ;
  Data_Get_Struct(self, xmlNode, node);
  
  path = xmlGetNodePath(node);
  VALUE rval = NOKOGIRI_STR_NEW2(path, node->doc->encoding);
  xmlFree(path);
  return rval ;
}
pointer_id click to toggle source

Get the internal pointer number

static VALUE pointer_id(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);

  return INT2NUM((int)(node));
}
previous() click to toggle source

Alias for previous_sibling

previous_sibling click to toggle source

Returns the previous sibling node

static VALUE previous_sibling(VALUE self)
{
  xmlNodePtr node, sibling;
  Data_Get_Struct(self, xmlNode, node);

  sibling = node->prev;
  if(!sibling) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, sibling);
}
Also aliased as: previous
read_only?() click to toggle source

Is this a read only node?

# File lib/nokogiri/xml/node.rb, line 372
      def read_only?
        # According to gdome2, these are read-only node types
        [NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type)
      end
remove() click to toggle source

Alias for unlink

remove_attribute(name) click to toggle source

Remove the attribute named name

# File lib/nokogiri/xml/node.rb, line 254
      def remove_attribute name
        attributes[name].remove if key? name
      end
Also aliased as: delete
replace(new_node) click to toggle source

replace this Node with the new_node in the Document.

# File lib/nokogiri/xml/node.rb, line 465
      def replace new_node
        if new_node.is_a?(Document) || !new_node.is_a?(XML::Node)
          raise ArgumentError, "Node.replace requires a Node argument, and cannot accept a Document.\n(You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)\n"
        end
        replace_with_node new_node
      end
search(*paths) click to toggle source

Search this node for paths. paths can be XPath or CSS, and an optional hash of namespaces may be appended. See Node#xpath and Node#css.

# File lib/nokogiri/xml/node.rb, line 94
      def search *paths
        ns = paths.last.is_a?(Hash) ? paths.pop :
          (document.root ? document.root.namespaces : {})
        xpath(*(paths.map { |path|
          path = path.to_s
          path =~ /^(\.\/|\/)/ ? path : CSS.xpath_for(
            path,
            :prefix => ".//",
            :ns     => ns
          )
        }.flatten.uniq) + [ns])
      end
Also aliased as: /
serialize(*args, &block) click to toggle source

Serialize Node using options. Save options can also be set using a block. See SaveOptions.

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
# File lib/nokogiri/xml/node.rb, line 498
      def serialize *args, &block
        options = args.first.is_a?(Hash) ? args.shift : {
          :encoding   => args[0],
          :save_with  => args[1] || SaveOptions::FORMAT
        }

        io = StringIO.new
        write_to io, options, &block
        io.rewind
        io.read
      end
set_namespace(namespace) click to toggle source

(Not documented)

# File lib/nokogiri/ffi/xml/node.rb, line 105
      def set_namespace(namespace)
        LibXML.xmlSetNs(cstruct, namespace.cstruct)
        self
      end
swap(data) click to toggle source

Swap this Node for new nodes made from data

# File lib/nokogiri/xml/node.rb, line 287
      def swap data
        before(data)
        remove
        self
      end
text() click to toggle source

Alias for content

Also aliased as: to_str
text?() click to toggle source

Returns true if this is a Text node

# File lib/nokogiri/xml/node.rb, line 358
      def text?
        type == TEXT_NODE
      end
to_html(options = {}) click to toggle source

Serialize this Node to HTML

  doc.to_html

See Node#write_to for a list of options. For formatted output, use Node#to_xhtml instead.

# File lib/nokogiri/xml/node.rb, line 517
      def to_html options = {}
        # FIXME: this is a hack around broken libxml versions
        return dump_html if %w[2 6] === LIBXML_VERSION.split('.')[0..1]

        options[:save_with] ||= SaveOptions::FORMAT |
                                SaveOptions::NO_DECLARATION |
                                SaveOptions::NO_EMPTY_TAGS |
                                SaveOptions::AS_HTML

        serialize(options)
      end
to_s() click to toggle source

Turn this node in to a string. If the document is HTML, this method returns html. If the document is XML, this method returns XML.

# File lib/nokogiri/xml/node.rb, line 386
      def to_s
        document.xml? ? to_xml : to_html
      end
to_str() click to toggle source

Alias for text

to_xhtml(options = {}) click to toggle source

Serialize this Node to XHTML using options

  doc.to_xhtml(:indent => 5, :encoding => 'UTF-8')

See Node#write_to for a list of options

# File lib/nokogiri/xml/node.rb, line 549
      def to_xhtml options = {}
        # FIXME: this is a hack around broken libxml versions
        return dump_html if %w[2 6] === LIBXML_VERSION.split('.')[0..1]

        options[:save_with] ||= SaveOptions::FORMAT |
                                SaveOptions::NO_DECLARATION |
                                SaveOptions::NO_EMPTY_TAGS |
                                SaveOptions::AS_XHTML

        serialize(options)
      end
to_xml(options = {}) click to toggle source

Serialize this Node to XML using options

  doc.to_xml(:indent => 5, :encoding => 'UTF-8')

See Node#write_to for a list of options

# File lib/nokogiri/xml/node.rb, line 535
      def to_xml options = {}
        encoding = nil

        options[:save_with] ||= SaveOptions::FORMAT | SaveOptions::AS_XML

        serialize(options)
      end
traverse(&block) click to toggle source

Yields self and all children to block recursively.

# File lib/nokogiri/xml/node.rb, line 452
      def traverse &block
        children.each{|j| j.traverse(&block) }
        block.call(self)
      end
type() click to toggle source

Alias for node_type

values() click to toggle source

Get the attribute values for this Node.

# File lib/nokogiri/xml/node.rb, line 234
      def values
        attribute_nodes.map { |node| node.value }
      end
write_html_to(io, options = {}) click to toggle source

Write Node as HTML to io with options

See Node#write_to for a list of options

# File lib/nokogiri/xml/node.rb, line 596
      def write_html_to io, options = {}
        # FIXME: this is a hack around broken libxml versions
        return (io << dump_html) if %w[2 6] === LIBXML_VERSION.split('.')[0..1]

        options[:save_with] ||= SaveOptions::FORMAT |
          SaveOptions::NO_DECLARATION |
          SaveOptions::NO_EMPTY_TAGS |
          SaveOptions::AS_HTML
        write_to io, options
      end
write_to(io, *options) click to toggle source

Write 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 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
# File lib/nokogiri/xml/node.rb, line 578
      def write_to io, *options
        options       = options.first.is_a?(Hash) ? options.shift : {}
        encoding      = options[:encoding] || options[0]
        save_options  = options[:save_with] || options[1] || SaveOptions::FORMAT
        indent_text   = options[:indent_text] || ' '
        indent_times  = options[:indent] || 2


        config = SaveOptions.new(save_options)
        yield config if block_given?

        native_write_to(io, encoding, indent_text * indent_times, config.options)
      end
write_xhtml_to(io, options = {}) click to toggle source

Write Node as XHTML to io with options

See Node#write_to for a list of options

# File lib/nokogiri/xml/node.rb, line 611
      def write_xhtml_to io, options = {}
        # FIXME: this is a hack around broken libxml versions
        return (io << dump_html) if %w[2 6] === LIBXML_VERSION.split('.')[0..1]

        options[:save_with] ||= SaveOptions::FORMAT |
          SaveOptions::NO_DECLARATION |
          SaveOptions::NO_EMPTY_TAGS |
          SaveOptions::AS_XHTML
        write_to io, options
      end
write_xml_to(io, options = {}) click to toggle source

Write Node as XML to io with options

  doc.write_xml_to io, :encoding => 'UTF-8'

See Node#write_to for a list of options

# File lib/nokogiri/xml/node.rb, line 628
      def write_xml_to io, options = {}
        options[:save_with] ||= SaveOptions::FORMAT | SaveOptions::AS_XML
        write_to io, options
      end
xml?() click to toggle source

Returns true if this is an XML::Document node

# File lib/nokogiri/xml/node.rb, line 348
      def xml?
        type == DOCUMENT_NODE
      end
xpath(*paths) click to toggle source

Search this node for XPath paths. paths must be one or more XPath queries. A hash of namespaces may be appended. For example:

  node.xpath('.//title')
  node.xpath('.//foo:name', { 'foo' => 'http://example.org/' })
  node.xpath('.//xmlns:name', node.root.namespaces)

Custom XPath functions may also be defined. To define custom functions create a class and implement the # function you want to define. For example:

  node.xpath('.//title[regex(., "\w+")]', Class.new {
    def regex node_set, regex
      node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
    end
  }.new)
# File lib/nokogiri/xml/node.rb, line 126
      def xpath *paths
        # Pop off our custom function handler if it exists
        handler = ![
          Hash, String, Symbol
        ].include?(paths.last.class) ? paths.pop : nil

        ns = paths.last.is_a?(Hash) ? paths.pop :
          (document.root ? document.root.namespaces : {})

        return NodeSet.new(document) unless document

        sets = paths.map { |path|
          ctx = XPathContext.new(self)
          ctx.register_namespaces(ns)
          set = ctx.evaluate(path, handler).node_set
          set.document = document
          document.decorate(set)
          set
        }
        return sets.first if sets.length == 1

        NodeSet.new(document) do |combined|
          document.decorate(combined)
          sets.each do |set|
            set.each do |node|
              combined << node
            end
          end
        end
      end

Private Instance Methods

compare(other) click to toggle source

Compare this Node to other with respect to their Document

static VALUE compare(VALUE self, VALUE _other)
{
  xmlNodePtr node, other;
  Data_Get_Struct(self, xmlNode, node);
  Data_Get_Struct(_other, xmlNode, other);

  return INT2NUM(xmlXPathCmpNodes(other, node));
}
dump_html click to toggle source

Returns the Node as html.

static VALUE dump_html(VALUE self)
{
  xmlBufferPtr buf ;
  xmlNodePtr node ;
  Data_Get_Struct(self, xmlNode, node);

  if(node->doc->type == XML_DOCUMENT_NODE)
    return rb_funcall(self, rb_intern("to_xml"), 0);

  buf = xmlBufferCreate() ;
  htmlNodeDump(buf, node->doc, node);
  VALUE html = NOKOGIRI_STR_NEW2(buf->content, node->doc->encoding);
  xmlBufferFree(buf);
  return html ;
}
get(attribute) click to toggle source

Get the value for attribute

static VALUE get(VALUE self, VALUE attribute)
{
  xmlNodePtr node;
  xmlChar* propstr ;
  VALUE rval ;
  Data_Get_Struct(self, xmlNode, node);

  if(attribute == Qnil) return Qnil;

  propstr = xmlGetProp(node, (xmlChar *)StringValuePtr(attribute));

  if(NULL == propstr) return Qnil;

  rval = NOKOGIRI_STR_NEW2(propstr, node->doc->encoding);

  xmlFree(propstr);
  return rval ;
}
content= click to toggle source

Set the content for this Node

static VALUE set_content(VALUE self, VALUE content)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  xmlNodeSetContent(node, (xmlChar *)StringValuePtr(content));
  return content;
}
native_write_to(io, encoding, options) click to toggle source

Write this Node to io with encoding and options

static VALUE native_write_to(
    VALUE self,
    VALUE io,
    VALUE encoding,
    VALUE indent_string,
    VALUE options
) 
set_namespace(namespace) click to toggle source

Set the namespace to namespace

static VALUE set_namespace(VALUE self, VALUE namespace)
{
  xmlNodePtr node;
  xmlNsPtr ns;

  Data_Get_Struct(self, xmlNode, node);
  Data_Get_Struct(namespace, xmlNs, ns);

  xmlSetNs(node, ns);

  return self;
}

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.