Class: Nokogiri::XML::Node

Inherits:
Object
  • Object
show all
Includes:
Enumerable, PP::Node
Defined in:
lib/nokogiri/xml/node.rb,
lib/nokogiri/xml/node/save_options.rb,
ext/nokogiri/xml_dtd.c,
ext/nokogiri/xml_attr.c,
ext/nokogiri/xml_node.c,
ext/nokogiri/xml_text.c,
ext/nokogiri/xml_cdata.c,
ext/nokogiri/xml_comment.c,
ext/nokogiri/xml_document.c,
ext/nokogiri/html_document.c,
ext/nokogiri/xml_entity_decl.c,
ext/nokogiri/xml_element_decl.c,
ext/nokogiri/xml_attribute_decl.c,
ext/nokogiri/xml_entity_reference.c,
ext/nokogiri/xml_document_fragment.c,
ext/nokogiri/xml_processing_instruction.c

Overview

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:

  • Nokogiri::XML::Node#parent

  • Nokogiri::XML::Node#children

  • Nokogiri::XML::Node#next

  • Nokogiri::XML::Node#previous

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

Defined Under Namespace

Classes: SaveOptions

Constant Summary collapse

ELEMENT_NODE =

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

1
ATTRIBUTE_NODE =

Attribute node type

2
TEXT_NODE =

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

3
CDATA_SECTION_NODE =

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

4
ENTITY_REF_NODE =

Entity reference node type

5
ENTITY_NODE =

Entity node type

6
PI_NODE =

PI node type

7
COMMENT_NODE =

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

8
DOCUMENT_NODE =

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

9
DOCUMENT_TYPE_NODE =

Document type node type

10
DOCUMENT_FRAG_NODE =

Document fragment node type

11
NOTATION_NODE =

Notation node type

12
HTML_DOCUMENT_NODE =

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

13
DTD_NODE =

DTD node type

14
ELEMENT_DECL =

Element declaration type

15
ATTRIBUTE_DECL =

Attribute declaration type

16
ENTITY_DECL =

Entity declaration type

17
NAMESPACE_DECL =

Namespace declaration type

18
XINCLUDE_START =

XInclude start type

19
XINCLUDE_END =

XInclude end type

20
DOCB_DOCUMENT_NODE =

DOCB document node type

21

Class Method Summary collapse

Instance Method Summary collapse

Methods included from PP::Node

#inspect, #pretty_print

Constructor Details

#initialize(name, document) ⇒ Node

:nodoc:



83
84
85
# File 'lib/nokogiri/xml/node.rb', line 83

def initialize name, document # :nodoc:
  # ... Ya.  This is empty on purpose.
end

Class Method Details

.new(name, document) ⇒ Object

Create a new node with name sharing GC lifecycle with document



1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
# File 'ext/nokogiri/xml_node.c', line 1121

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

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

  Data_Get_Struct(document, xmlDoc, doc);

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

  rb_node = Nokogiri_wrap_xml_node(
      klass == cNokogiriXmlNode ? (VALUE)NULL : klass,
      node
  );
  rb_obj_call_init(rb_node, argc, argv);

  if(rb_block_given_p()) rb_yield(rb_node);

  return rb_node;
}

Instance Method Details

#<<(node_or_tags) ⇒ Object

Add node_or_tags as a child of this Node. node_or_tags can be a Nokogiri::XML::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.



288
289
290
291
# File 'lib/nokogiri/xml/node.rb', line 288

def << node_or_tags
  add_child node_or_tags
  self
end

#<=>(other) ⇒ Object

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



871
872
873
874
875
# File 'lib/nokogiri/xml/node.rb', line 871

def <=> other
  return nil unless other.is_a?(Nokogiri::XML::Node)
  return nil unless document == other.document
  compare other
end

#==(other) ⇒ Object

Test to see if this Node is equal to other



718
719
720
721
722
# File 'lib/nokogiri/xml/node.rb', line 718

def == other
  return false unless other
  return false unless other.respond_to?(:pointer_id)
  pointer_id == other.pointer_id
end

#>(selector) ⇒ Object

Search this node’s immediate children using CSS selector selector



219
220
221
222
# File 'lib/nokogiri/xml/node.rb', line 219

def > selector
  ns = document.root.namespaces
  xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
end

#[](name) ⇒ Object Also known as: get_attribute, attr

Get the attribute value for the attribute name



253
254
255
256
# File 'lib/nokogiri/xml/node.rb', line 253

def [] name
  return nil unless key?(name.to_s)
  get(name.to_s)
end

#[]=(name, value) ⇒ Object Also known as: set_attribute

Set the attribute value for the attribute name to value



260
261
262
# File 'lib/nokogiri/xml/node.rb', line 260

def []= name, value
  set name.to_s, value
end

#accept(visitor) ⇒ Object

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



712
713
714
# File 'lib/nokogiri/xml/node.rb', line 712

def accept visitor
  visitor.visit(self)
end

#add_child(node_or_tags) ⇒ Object

Add node_or_tags as a child of this Node. node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.

Returns the reparented node (if node_or_tags is a Node), or NodeSet (if node_or_tags is a DocumentFragment, NodeSet, or string).

Also see related method <<.



271
272
273
274
275
276
277
278
279
# File 'lib/nokogiri/xml/node.rb', line 271

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 n }
  else
    add_child_node node_or_tags
  end
  node_or_tags
end

#add_namespace_definition(prefix, href) ⇒ Object Also known as: add_namespace

Adds a namespace definition with prefix using href value. The result is as if parsed XML for this node had included an attribute ‘xmlns:prefix=value’. A default namespace for this node (“xmlns=”) can be added by passing ‘nil’ for prefix. Namespaces added this way will not show up in #attributes, but they will be included as an xmlns attribute when the node is serialized to XML.



1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
# File 'ext/nokogiri/xml_node.c', line 1083

static VALUE add_namespace_definition(VALUE self, VALUE prefix, VALUE href)
{
  xmlNodePtr node, namespacee;
  xmlNsPtr ns;

  Data_Get_Struct(self, xmlNode, node);
  namespacee = node ;

  ns = xmlSearchNs(
      node->doc,
      node,
      (const xmlChar *)(NIL_P(prefix) ? NULL : StringValuePtr(prefix))
  );

  if(!ns) {
    if (node->type != XML_ELEMENT_NODE) {
      namespacee = node->parent;
    }
    ns = xmlNewNs(
        namespacee,
        (const xmlChar *)StringValuePtr(href),
        (const xmlChar *)(NIL_P(prefix) ? NULL : StringValuePtr(prefix))
    );
  }

  if (!ns) return Qnil ;

  if(NIL_P(prefix) || node != namespacee) xmlSetNs(node, ns);

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

#add_next_sibling(node_or_tags) ⇒ Object Also known as: next=

Insert node_or_tags after this Node (as a sibling). node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.

Returns the reparented node (if node_or_tags is a Node), or NodeSet (if node_or_tags is a DocumentFragment, NodeSet, or string).

Also see related method after.

Raises:

  • (ArgumentError)


325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/nokogiri/xml/node.rb', line 325

def add_next_sibling node_or_tags
  raise ArgumentError.new("A document may not have multiple root nodes.") if parent.is_a?(XML::Document)
  
  node_or_tags = coerce(node_or_tags)
  if node_or_tags.is_a?(XML::NodeSet)
    if text?
      pivot = Nokogiri::XML::Node.new 'dummy', document
      add_next_sibling_node pivot
    else
      pivot = self
    end
    node_or_tags.reverse_each { |n| pivot.send :add_next_sibling_node, n }
    pivot.unlink if text?
  else
    add_next_sibling_node node_or_tags
  end
  node_or_tags
end

#add_previous_sibling(node_or_tags) ⇒ Object Also known as: previous=

Insert node_or_tags before this Node (as a sibling). node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.

Returns the reparented node (if node_or_tags is a Node), or NodeSet (if node_or_tags is a DocumentFragment, NodeSet, or string).

Also see related method before.

Raises:

  • (ArgumentError)


299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
# File 'lib/nokogiri/xml/node.rb', line 299

def add_previous_sibling node_or_tags
  raise ArgumentError.new("A document may not have multiple root nodes.") if parent.is_a?(XML::Document) && !node_or_tags.is_a?(XML::ProcessingInstruction)

  node_or_tags = coerce(node_or_tags)
  if node_or_tags.is_a?(XML::NodeSet)
    if text?
      pivot = Nokogiri::XML::Node.new 'dummy', document
      add_previous_sibling_node pivot
    else
      pivot = self
    end
    node_or_tags.each { |n| pivot.send :add_previous_sibling_node, n }
    pivot.unlink if text?
  else
    add_previous_sibling_node node_or_tags
  end
  node_or_tags
end

#after(node_or_tags) ⇒ Object

Insert node_or_tags after this node (as a sibling). node_or_tags can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.

Returns self, to support chaining of calls.

Also see related method add_next_sibling.



363
364
365
366
# File 'lib/nokogiri/xml/node.rb', line 363

def after node_or_tags
  add_next_sibling node_or_tags
  self
end

#ancestors(selector = nil) ⇒ Object

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



653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/nokogiri/xml/node.rb', line 653

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

  NodeSet.new(document, parents.find_all { |parent|
    root.search(selector).include?(parent)
  })
end

#at(path, ns = document.root ? document.root.namespaces : {}) ⇒ Object Also known as: %

Search for the first occurrence of path.

Returns nil if nothing is found, otherwise a Node.



228
229
230
# File 'lib/nokogiri/xml/node.rb', line 228

def at path, ns = document.root ? document.root.namespaces : {}
  search(path, ns).first
end

#at_css(*rules) ⇒ Object

Search this node for the first occurrence of CSS rules. Equivalent to css(rules).first See Node#css for more information.



247
248
249
# File 'lib/nokogiri/xml/node.rb', line 247

def at_css *rules
  css(*rules).first
end

#at_xpath(*paths) ⇒ Object

Search this node for the first occurrence of XPath paths. Equivalent to xpath(paths).first See Node#xpath for more information.



238
239
240
# File 'lib/nokogiri/xml/node.rb', line 238

def at_xpath *paths
  xpath(*paths).first
end

#attribute(name) ⇒ Object

Get the attribute node with name



748
749
750
751
752
753
754
755
756
757
# File 'ext/nokogiri/xml_node.c', line 748

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_nodesObject

returns a list containing the Node attributes.



783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'ext/nokogiri/xml_node.c', line 783

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

    Data_Get_Struct(self, xmlNode, node);

    attr = rb_ary_new();
    Nokogiri_xml_node_properties(node, attr);

    return attr ;
}

#attribute_with_ns(name, namespace) ⇒ Object

Get the attribute node with name and namespace



765
766
767
768
769
770
771
772
773
774
775
# File 'ext/nokogiri/xml_node.c', line 765

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),
      NIL_P(namespace) ? NULL : (xmlChar *)StringValuePtr(namespace));

  if(! prop) return Qnil;
  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)prop);
}

#attributesObject

Returns a hash containing the node’s attributes. The key is the attribute name without any namespace, the value is a Nokogiri::XML::Attr representing the attribute. If you need to distinguish attributes with the same name, with different namespaces use #attribute_nodes instead.



464
465
466
467
468
# File 'lib/nokogiri/xml/node.rb', line 464

def attributes
  Hash[attribute_nodes.map { |node|
    [node.node_name, node]
  }]
end

#before(node_or_tags) ⇒ Object

Insert node_or_tags before this node (as a sibling). node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.

Returns self, to support chaining of calls.

Also see related method add_previous_sibling.



351
352
353
354
# File 'lib/nokogiri/xml/node.rb', line 351

def before node_or_tags
  add_previous_sibling node_or_tags
  self
end

#blank?Boolean

Is this node blank?

Returns:

  • (Boolean)


404
405
406
407
408
409
# File 'ext/nokogiri/xml_node.c', line 404

static VALUE blank_eh(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  return (1 == xmlIsBlankNode(node)) ? Qtrue : Qfalse ;
}

#canonicalize(mode = XML::XML_C14N_1_0, inclusive_namespaces = nil, with_comments = false) ⇒ Object



891
892
893
894
895
896
897
# File 'lib/nokogiri/xml/node.rb', line 891

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

#cdata?Boolean

Returns true if this is a CDATA

Returns:

  • (Boolean)


586
587
588
# File 'lib/nokogiri/xml/node.rb', line 586

def cdata?
  type == CDATA_SECTION_NODE
end

#childObject

Returns the child node



576
577
578
579
580
581
582
583
584
585
# File 'ext/nokogiri/xml_node.c', line 576

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);
}

#childrenObject

Get the list of children for this node as a NodeSet



503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
# File 'ext/nokogiri/xml_node.c', line 503

static VALUE children(VALUE self)
{
  xmlNodePtr node;
  xmlNodePtr child;
  xmlNodeSetPtr set;
  VALUE document;
  VALUE node_set;

  Data_Get_Struct(self, xmlNode, node);

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

  document = DOC_RUBY_OBJECT(node->doc);

  if(!child) return Nokogiri_wrap_xml_node_set(set, document);

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

  node_set = Nokogiri_wrap_xml_node_set(set, document);

  return node_set;
}

#children=(node_or_tags) ⇒ Object

Set the inner html for this Node node_or_tags node_or_tags can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.

Returns the reparented node (if node_or_tags is a Node), or NodeSet (if node_or_tags is a DocumentFragment, NodeSet, or string).

Also see related method inner_html=



387
388
389
390
391
392
393
394
395
396
# File 'lib/nokogiri/xml/node.rb', line 387

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 n }
  else
    add_child_node node_or_tags
  end
  node_or_tags
end

#comment?Boolean

Returns true if this is a Comment

Returns:

  • (Boolean)


581
582
583
# File 'lib/nokogiri/xml/node.rb', line 581

def comment?
  type == COMMENT_NODE
end

#contentObject Also known as: text, inner_text

Returns the content for this Node



918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
# File 'ext/nokogiri/xml_node.c', line 918

static VALUE get_content(VALUE self)
{
  xmlNodePtr node;
  xmlChar * content;

  Data_Get_Struct(self, xmlNode, node);

  content = xmlNodeGetContent(node);
  if(content) {
    VALUE rval = NOKOGIRI_STR_NEW2(content);
    xmlFree(content);
    return rval;
  }
  return Qnil;
}

#content=(string) ⇒ Object

Set the Node’s content to a Text node containing string. The string gets XML escaped, not interpreted as markup.



542
543
544
# File 'lib/nokogiri/xml/node.rb', line 542

def content= string
  self.native_content = encode_special_chars(string.to_s)
end

#create_external_subset(name, external_id, system_id) ⇒ Object

Create an external subset



285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
# File 'ext/nokogiri/xml_node.c', line 285

static VALUE create_external_subset(VALUE self, VALUE name, VALUE external_id, VALUE system_id)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Data_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 *)StringValuePtr(name),
      NIL_P(external_id) ? NULL : (const xmlChar *)StringValuePtr(external_id),
      NIL_P(system_id)   ? NULL : (const xmlChar *)StringValuePtr(system_id)
  );

  if(!dtd) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)dtd);
}

#create_internal_subset(name, external_id, system_id) ⇒ Object

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">


254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'ext/nokogiri/xml_node.c', line 254

static VALUE create_internal_subset(VALUE self, VALUE name, VALUE external_id, VALUE system_id)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Data_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 *)StringValuePtr(name),
      NIL_P(external_id) ? NULL : (const xmlChar *)StringValuePtr(external_id),
      NIL_P(system_id)   ? NULL : (const xmlChar *)StringValuePtr(system_id)
  );

  if(!dtd) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)dtd);
}

#css(*rules) ⇒ Object

call-seq: css *rules, [namespace-bindings, custom-pseudo-class]

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')

A hash of namespace bindings may be appended. For example:

node.css('bike|tire', {'bike' => 'http://schwinn.com/'})

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)

Note that the CSS query string is case-sensitive with regards to your document type. That is, if you’re looking for “H1” in an HTML document, you’ll never find anything, since HTML tags will match only lowercase CSS queries. However, “H1” might be found in an XML document, where tags names are case-sensitive (e.g., “H1” is distinct from “h1”).



205
206
207
208
209
210
211
212
213
214
215
# File 'lib/nokogiri/xml/node.rb', line 205

def css *rules
  rules, handler, ns, binds = extract_params(rules)

  prefix = "#{implied_xpath_context}/"

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

  xpath(*rules)
end

#css_pathObject

Get the path to this node as a CSS expression



644
645
646
647
648
# File 'lib/nokogiri/xml/node.rb', line 644

def css_path
  path.split(/\//).map { |part|
    part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
  }.compact.join(' > ')
end

#decorate!Object

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



89
90
91
# File 'lib/nokogiri/xml/node.rb', line 89

def decorate!
  document.decorate(self)
end

#default_namespace=(url) ⇒ Object

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. A default namespace set with this method will now show up in #attributes, but when this node is serialized to XML an “xmlns” attribute will appear. See also #namespace and #namespace=



679
680
681
# File 'lib/nokogiri/xml/node.rb', line 679

def default_namespace= url
  add_namespace_definition(nil, url)
end

#descriptionObject

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



613
614
615
616
# File 'lib/nokogiri/xml/node.rb', line 613

def description
  return nil if document.xml?
  Nokogiri::HTML::ElementDescription[name]
end

#do_xinclude(options = XML::ParseOptions::DEFAULT_XML) {|options| ... } ⇒ Object

Do xinclude substitution on the subtree below node. If given a block, a Nokogiri::XML::ParseOptions object initialized from options, will be passed to it, allowing more convenient modification of the parser options.

Yields:

  • (options)


881
882
883
884
885
886
887
888
889
# File 'lib/nokogiri/xml/node.rb', line 881

def do_xinclude options = XML::ParseOptions::DEFAULT_XML, &block
  options = Nokogiri::XML::ParseOptions.new(options) if Fixnum === options

  # give options to user
  yield options if block_given?

  # call c extension
  process_xincludes(options.to_i)
end

#documentObject

Get the document for this Node



197
198
199
200
201
202
# File 'ext/nokogiri/xml_node.c', line 197

static VALUE document(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  return DOC_RUBY_OBJECT(node->doc);
}

#dupObject Also known as: clone

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.



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'ext/nokogiri/xml_node.c', line 365

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

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

  Data_Get_Struct(self, xmlNode, node);

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

  nokogiri_root_node(dup);

  return Nokogiri_wrap_xml_node(rb_obj_class(self), dup);
}

#eachObject

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



484
485
486
487
488
# File 'lib/nokogiri/xml/node.rb', line 484

def each
  attribute_nodes.each { |node|
    yield [node.node_name, node.value]
  }
end

#element?Boolean Also known as: elem?

Returns true if this is an Element node

Returns:

  • (Boolean)


626
627
628
# File 'lib/nokogiri/xml/node.rb', line 626

def element?
  type == ELEMENT_NODE
end

#element_childrenObject Also known as: elements

Get the list of children for this node as a NodeSet. All nodes will be element nodes.

Example:

@doc.root.element_children.all? { |x| x.element? } # => true


542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
# File 'ext/nokogiri/xml_node.c', line 542

static VALUE element_children(VALUE self)
{
  xmlNodePtr node;
  xmlNodePtr child;
  xmlNodeSetPtr set;
  VALUE document;
  VALUE node_set;

  Data_Get_Struct(self, xmlNode, node);

  child = xmlFirstElementChild(node);
  set = xmlXPathNodeSetCreate(child);

  document = DOC_RUBY_OBJECT(node->doc);

  if(!child) return Nokogiri_wrap_xml_node_set(set, document);

  child = xmlNextElementSibling(child);
  while(NULL != child) {
    xmlXPathNodeSetAddUnique(set, child);
    child = xmlNextElementSibling(child);
  }

  node_set = Nokogiri_wrap_xml_node_set(set, document);

  return node_set;
}

#encode_special_chars(string) ⇒ Object

Encode any special characters in string



224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
# File 'ext/nokogiri/xml_node.c', line 224

static VALUE encode_special_chars(VALUE self, VALUE string)
{
  xmlNodePtr node;
  xmlChar *encoded;
  VALUE encoded_str;

  Data_Get_Struct(self, xmlNode, node);
  encoded = xmlEncodeSpecialChars(
      node->doc,
      (const xmlChar *)StringValuePtr(string)
  );

  encoded_str = NOKOGIRI_STR_NEW2(encoded);
  xmlFree(encoded);

  return encoded_str;
}

#external_subsetObject

Get the external subset



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
# File 'ext/nokogiri/xml_node.c', line 316

static VALUE external_subset(VALUE self)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Data_Get_Struct(self, xmlNode, node);

  if(!node->doc) return Qnil;

  doc = node->doc;
  dtd = doc->extSubset;

  if(!dtd) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)dtd);
}

#first_element_childObject

Returns the first child node of this node that is an element.

Example:

@doc.root.first_element_child.element? # => true


597
598
599
600
601
602
603
604
605
606
# File 'ext/nokogiri/xml_node.c', line 597

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

  child = xmlFirstElementChild(node);
  if(!child) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, child);
}

#fragment(tags) ⇒ Object

Create a DocumentFragment containing tags that is relative to this context node.



506
507
508
509
# File 'lib/nokogiri/xml/node.rb', line 506

def fragment tags
  type = document.html? ? Nokogiri::HTML : Nokogiri::XML
  type::DocumentFragment.new(document, tags, self)
end

#fragment?Boolean

Returns true if this is a DocumentFragment

Returns:

  • (Boolean)


606
607
608
# File 'lib/nokogiri/xml/node.rb', line 606

def fragment?
  type == DOCUMENT_FRAG_NODE
end

#html?Boolean

Returns true if this is an HTML::Document node

Returns:

  • (Boolean)


596
597
598
# File 'lib/nokogiri/xml/node.rb', line 596

def html?
  type == HTML_DOCUMENT_NODE
end

#inner_html(*args) ⇒ Object

Get the inner_html for this node’s Node#children



639
640
641
# File 'lib/nokogiri/xml/node.rb', line 639

def inner_html *args
  children.map { |x| x.to_html(*args) }.join
end

#inner_html=(node_or_tags) ⇒ Object

Set the inner html for this Node to node_or_tags node_or_tags can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.

Returns self.

Also see related method children=



375
376
377
378
# File 'lib/nokogiri/xml/node.rb', line 375

def inner_html= node_or_tags
  self.children = node_or_tags
  self
end

#internal_subsetObject

Get the internal subset



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
# File 'ext/nokogiri/xml_node.c', line 340

static VALUE internal_subset(VALUE self)
{
  xmlNodePtr node;
  xmlDocPtr doc;
  xmlDtdPtr dtd;

  Data_Get_Struct(self, xmlNode, node);

  if(!node->doc) return Qnil;

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

  if(!dtd) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)dtd);
}

#key?(attribute) ⇒ Boolean Also known as: has_attribute?

Returns true if attribute is set

Returns:

  • (Boolean)


635
636
637
638
639
640
641
642
# File 'ext/nokogiri/xml_node.c', line 635

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;
}

#keysObject

Get the attribute names for this Node.



478
479
480
# File 'lib/nokogiri/xml/node.rb', line 478

def keys
  attribute_nodes.map { |node| node.node_name }
end

#last_element_childObject

Returns the last child node of this node that is an element.

Example:

@doc.root.last_element_child.element? # => true


618
619
620
621
622
623
624
625
626
627
# File 'ext/nokogiri/xml_node.c', line 618

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

  child = xmlLastElementChild(node);
  if(!child) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, child);
}

#lineObject

Returns the line for this Node



1064
1065
1066
1067
1068
1069
1070
# File 'ext/nokogiri/xml_node.c', line 1064

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

  return INT2NUM(xmlGetLineNo(node));
}

#matches?(selector) ⇒ Boolean

Returns true if this Node matches selector

Returns:

  • (Boolean)


499
500
501
# File 'lib/nokogiri/xml/node.rb', line 499

def matches? selector
  ancestors.last.search(selector).include?(self)
end

#namespaceObject

returns the default namespace set on this node (as with an “xmlns=” attribute), as a Namespace object.



805
806
807
808
809
810
811
812
813
814
# File 'ext/nokogiri/xml_node.c', line 805

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) ⇒ Object

Set the default namespace on this node (as would be defined with an “xmlns=” attribute in XML source), as a Namespace object ns. Note that a Namespace added this way will NOT be serialized as an xmlns attribute for this node. You probably want #default_namespace= instead, or perhaps #add_namespace_definition with a nil prefix argument.



690
691
692
693
694
695
696
697
698
699
700
701
# File 'lib/nokogiri/xml/node.rb', line 690

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

#namespace_definitionsObject

returns namespaces defined on self element directly, as an array of Namespace objects. Includes both a default namespace (as in“xmlns=”), and prefixed namespaces (as in “xmlns:prefix=”).



822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
# File 'ext/nokogiri/xml_node.c', line 822

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

  Data_Get_Struct(self, xmlNode, node);

  list = rb_ary_new();

  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;
}

#namespace_scopesObject

returns namespaces in scope for self – those defined on self element directly or any ancestor node – as an array of Namespace objects. Default namespaces (“xmlns=” style) for self are included in this array; Default namespaces for ancestors, however, are not. See also #namespaces



854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
# File 'ext/nokogiri/xml_node.c', line 854

static VALUE namespace_scopes(VALUE self)
{
  xmlNodePtr node ;
  VALUE list;
  xmlNsPtr *ns_list;
  int j;

  Data_Get_Struct(self, xmlNode, node);

  list = rb_ary_new();
  ns_list = xmlGetNsList(node->doc, node);

  if(!ns_list) return list;

  for (j = 0 ; ns_list[j] != NULL ; ++j) {
    rb_ary_push(list, Nokogiri_wrap_xml_namespace(node->doc, ns_list[j]));
  }

  xmlFree(ns_list);
  return list;
}

#namespaced_key?(attribute, namespace) ⇒ Boolean

Returns true if attribute is set with namespace

Returns:

  • (Boolean)


650
651
652
653
654
655
656
657
658
# File 'ext/nokogiri/xml_node.c', line 650

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),
        NIL_P(namespace) ? NULL : (xmlChar *)StringValuePtr(namespace)))
    return Qtrue;
  return Qfalse;
}

#namespacesObject

Returns a Hash of => value for all namespaces on this node and its ancestors.

This method returns the same namespaces as #namespace_scopes.

Returns namespaces in scope for self – those defined on self element directly or any ancestor node – as a Hash of attribute-name/value pairs. Note that the keys in this hash XML attributes that would be used to define this namespace, such as “xmlns:prefix”, not just the prefix. Default namespace set on self will be included with key “xmlns”. However, default namespaces set on ancestor will NOT be, even if self has no explicit default namespace.



567
568
569
570
571
572
573
574
575
576
577
578
# File 'lib/nokogiri/xml/node.rb', line 567

def namespaces
  Hash[namespace_scopes.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]
  }]
end

#next_elementObject

Returns the next Nokogiri::XML::Element type sibling node.



451
452
453
454
455
456
457
458
459
460
# File 'ext/nokogiri/xml_node.c', line 451

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

  sibling = xmlNextElementSibling(node);
  if(!sibling) return Qnil;

  return Nokogiri_wrap_xml_node(Qnil, sibling);
}

#next_siblingObject Also known as: next

Returns the next sibling node



417
418
419
420
421
422
423
424
425
426
# File 'ext/nokogiri/xml_node.c', line 417

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) ;
}

#nameObject Also known as: name

Returns the name for this Node



977
978
979
980
981
982
983
984
# File 'ext/nokogiri/xml_node.c', line 977

static VALUE get_name(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  if(node->name)
    return NOKOGIRI_STR_NEW2(node->name);
  return Qnil;
}

#name=(new_name) ⇒ Object Also known as: name=

Set the name for this Node



963
964
965
966
967
968
969
# File 'ext/nokogiri/xml_node.c', line 963

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;
}

#node_typeObject Also known as: type

Get the type for this Node



882
883
884
885
886
887
# File 'ext/nokogiri/xml_node.c', line 882

static VALUE node_type(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  return INT2NUM((long)node->type);
}

#parentObject

Get the parent Node for this Node



946
947
948
949
950
951
952
953
954
955
# File 'ext/nokogiri/xml_node.c', line 946

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) ⇒ Object

Set the parent Node for this Node



548
549
550
551
# File 'lib/nokogiri/xml/node.rb', line 548

def parent= parent_node
  parent_node.add_child(self)
  parent_node
end

#parse(string_or_io, options = nil) {|options| ... } ⇒ Object

Parse string_or_io as a document fragment within the context of this node. Returns a XML::NodeSet containing the nodes parsed from string_or_io.

Yields:

  • (options)


515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
# File 'lib/nokogiri/xml/node.rb', line 515

def parse string_or_io, options = nil
  options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)
  if Fixnum === options
    options = Nokogiri::XML::ParseOptions.new(options)
  end
  # Give the options to the user
  yield options if block_given?

  contents = string_or_io.respond_to?(:read) ?
    string_or_io.read :
    string_or_io

  return Nokogiri::XML::NodeSet.new(document) if contents.empty?

  ##
  # This is a horrible hack, but I don't care. See #313 for background.
  error_count = document.errors.length
  node_set = in_context(contents, options.to_i)
  if node_set.empty? and document.errors.length > error_count and options.recover?
    fragment = Nokogiri::HTML::DocumentFragment.parse contents
    node_set = fragment.children
  end
  node_set
end

#pathObject

Returns the path associated with this Node



992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
# File 'ext/nokogiri/xml_node.c', line 992

static VALUE path(VALUE self)
{
  xmlNodePtr node;
  xmlChar *path ;
  VALUE rval;

  Data_Get_Struct(self, xmlNode, node);

  path = xmlGetNodePath(node);
  rval = NOKOGIRI_STR_NEW2(path);
  xmlFree(path);
  return rval ;
}

#pointer_idObject

Get the internal pointer number



210
211
212
213
214
215
216
# File 'ext/nokogiri/xml_node.c', line 210

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

  return INT2NUM((long)(node));
}

#previous_elementObject

Returns the previous Nokogiri::XML::Element type sibling node.



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'ext/nokogiri/xml_node.c', line 468

static VALUE previous_element(VALUE self)
{
  xmlNodePtr node, sibling;
  Data_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 ? Nokogiri_wrap_xml_node(Qnil, sibling) : Qnil ;
}

#previous_siblingObject Also known as: previous

Returns the previous sibling node



434
435
436
437
438
439
440
441
442
443
# File 'ext/nokogiri/xml_node.c', line 434

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);
}

#read_only?Boolean

Is this a read only node?

Returns:

  • (Boolean)


620
621
622
623
# File 'lib/nokogiri/xml/node.rb', line 620

def read_only?
  # According to gdome2, these are read-only node types
  [NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type)
end

#remove_attribute(name) ⇒ Object Also known as: delete

Remove the attribute named name



492
493
494
# File 'lib/nokogiri/xml/node.rb', line 492

def remove_attribute name
  attributes[name].remove if key? name
end

#replace(node_or_tags) ⇒ Object

Replace this Node with node_or_tags. node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.

Returns the reparented node (if node_or_tags is a Node), or NodeSet (if node_or_tags is a DocumentFragment, NodeSet, or string).

Also see related method swap.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/nokogiri/xml/node.rb', line 405

def replace node_or_tags
  node_or_tags = coerce(node_or_tags)
  if node_or_tags.is_a?(XML::NodeSet)
    if text?
      replacee = Nokogiri::XML::Node.new 'dummy', document
      add_previous_sibling_node replacee
      unlink
    else
      replacee = self
    end
    node_or_tags.each { |n| replacee.add_previous_sibling n }
    replacee.unlink
  else
    replace_node node_or_tags
  end
  node_or_tags
end

#search(*paths) ⇒ Object Also known as: /

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.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/nokogiri/xml/node.rb', line 97

def search *paths
  # TODO use         paths, handler, ns, binds = extract_params(paths)
  ns = paths.last.is_a?(Hash) ? paths.pop :
    (document.root ? document.root.namespaces : {})

  prefix = "#{implied_xpath_context}/"

  xpath(*(paths.map { |path|
    path = path.to_s
    path =~ /^(\.\/|\/|\.\.|\.$)/ ? path : CSS.xpath_for(
      path,
      :prefix => prefix,
      :ns     => ns
    )
  }.flatten.uniq) + [ns])
end

#serialize(*args, &block) ⇒ Object

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


738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
# File 'lib/nokogiri/xml/node.rb', line 738

def serialize *args, &block
  options = args.first.is_a?(Hash) ? args.shift : {
    :encoding   => args[0],
    :save_with  => args[1]
  }

  encoding = options[:encoding] || document.encoding
  options[:encoding] = encoding

  outstring = ""
  if encoding && outstring.respond_to?(:force_encoding)
    outstring.force_encoding(Encoding.find(encoding))
  end
  io = StringIO.new(outstring)
  write_to io, options, &block
  io.string
end

#swap(node_or_tags) ⇒ Object

Swap this Node for node_or_tags node_or_tags can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.

Returns self, to support chaining of calls.

Also see related method replace.



430
431
432
433
# File 'lib/nokogiri/xml/node.rb', line 430

def swap node_or_tags
  replace node_or_tags
  self
end

#text?Boolean

Returns true if this is a Text node

Returns:

  • (Boolean)


601
602
603
# File 'lib/nokogiri/xml/node.rb', line 601

def text?
  type == TEXT_NODE
end

#to_html(options = {}) ⇒ Object

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.



763
764
765
766
767
768
769
770
# File 'lib/nokogiri/xml/node.rb', line 763

def to_html options = {}
  # FIXME: this is a hack around broken libxml versions
  return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]

  options[:save_with] |= SaveOptions::DEFAULT_HTML if options[:save_with]
  options[:save_with] = SaveOptions::DEFAULT_HTML unless options[:save_with]
  serialize(options)
end

#to_sObject

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.



634
635
636
# File 'lib/nokogiri/xml/node.rb', line 634

def to_s
  document.xml? ? to_xml : to_html
end

#to_xhtml(options = {}) ⇒ Object

Serialize this Node to XHTML using options

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

See Node#write_to for a list of options



789
790
791
792
793
794
795
796
# File 'lib/nokogiri/xml/node.rb', line 789

def to_xhtml options = {}
  # FIXME: this is a hack around broken libxml versions
  return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]

  options[:save_with] |= SaveOptions::DEFAULT_XHTML if options[:save_with]
  options[:save_with] = SaveOptions::DEFAULT_XHTML unless options[:save_with]
  serialize(options)
end

#to_xml(options = {}) ⇒ Object

Serialize this Node to XML using options

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

See Node#write_to for a list of options



778
779
780
781
# File 'lib/nokogiri/xml/node.rb', line 778

def to_xml options = {}
  options[:save_with] ||= SaveOptions::DEFAULT_XML
  serialize(options)
end

#traverse(&block) ⇒ Object

Yields self and all children to block recursively.



705
706
707
708
# File 'lib/nokogiri/xml/node.rb', line 705

def traverse &block
  children.each{|j| j.traverse(&block) }
  block.call(self)
end

Unlink this node from its current context.



389
390
391
392
393
394
395
396
# File 'ext/nokogiri/xml_node.c', line 389

static VALUE unlink_node(VALUE self)
{
  xmlNodePtr node;
  Data_Get_Struct(self, xmlNode, node);
  xmlUnlinkNode(node);
  nokogiri_root_node(node);
  return self;
}

#valuesObject

Get the attribute values for this Node.



472
473
474
# File 'lib/nokogiri/xml/node.rb', line 472

def values
  attribute_nodes.map { |node| node.value }
end

#write_html_to(io, options = {}) ⇒ Object

Write Node as HTML to io with options

See Node#write_to for a list of options



837
838
839
840
841
842
843
# File 'lib/nokogiri/xml/node.rb', line 837

def write_html_to io, options = {}
  # FIXME: this is a hack around broken libxml versions
  return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]

  options[:save_with] ||= SaveOptions::DEFAULT_HTML
  write_to io, options
end

#write_to(io, *options) {|config| ... } ⇒ Object

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

Yields:

  • (config)


815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
# File 'lib/nokogiri/xml/node.rb', line 815

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] || ' '

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

  native_write_to(io, encoding, indent_text * indent_times, config.options)
end

#write_xhtml_to(io, options = {}) ⇒ Object

Write Node as XHTML to io with options

See Node#write_to for a list of options



849
850
851
852
853
854
855
# File 'lib/nokogiri/xml/node.rb', line 849

def write_xhtml_to io, options = {}
  # FIXME: this is a hack around broken libxml versions
  return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]

  options[:save_with] ||= SaveOptions::DEFAULT_XHTML
  write_to io, options
end

#write_xml_to(io, options = {}) ⇒ Object

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



863
864
865
866
# File 'lib/nokogiri/xml/node.rb', line 863

def write_xml_to io, options = {}
  options[:save_with] ||= SaveOptions::DEFAULT_XML
  write_to io, options
end

#xml?Boolean

Returns true if this is an XML::Document node

Returns:

  • (Boolean)


591
592
593
# File 'lib/nokogiri/xml/node.rb', line 591

def xml?
  type == DOCUMENT_NODE
end

#xpath(*paths) ⇒ Object

call-seq: xpath *paths, [namespace-bindings, variable-bindings, custom-handler-class]

Search this node for XPath paths. paths must be one or more 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 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. Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. 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)


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/nokogiri/xml/node.rb', line 145

def xpath *paths
  return NodeSet.new(document) unless document

  paths, handler, ns, binds = extract_params(paths)

  sets = paths.map { |path|
    ctx = XPathContext.new(self)
    ctx.register_namespaces(ns)
    path = path.gsub(/xmlns:/, ' :') unless Nokogiri.uses_libxml?

    binds.each do |key,value|
      ctx.register_variable key.to_s, value
    end if binds

    ctx.evaluate(path, handler)
  }
  return sets.first if sets.length == 1

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