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
Element node type, see Nokogiri::XML::Node#element?
Attribute node type
Text node type, see Nokogiri::XML::Node#text?
CDATA node type, see Nokogiri::XML::Node#cdata?
Entity reference node type
Entity node type
PI node type
Comment node type, see Nokogiri::XML::Node#comment?
Document node type, see Nokogiri::XML::Node#xml?
Document type node type
Document fragment node type
Notation node type
HTML document node type, see Nokogiri::XML::Node#html?
DTD node type
Element declaration type
Attribute declaration type
Entity declaration type
Namespace declaration type
XInclude start type
XInclude end type
DOCB document node type
Create a new node with name sharing GC lifecycle with document
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; }
Compare two Node objects with respect to their Document. Nodes from different documents cannot be compared.
# File lib/nokogiri/xml/node.rb, line 767 767: def <=> other 768: return nil unless other.is_a?(Nokogiri::XML::Node) 769: return nil unless document == other.document 770: compare other 771: end
Test to see if this Node is equal to other
# File lib/nokogiri/xml/node.rb, line 606 606: def == other 607: return false unless other 608: return false unless other.respond_to?(:pointer_id) 609: pointer_id == other.pointer_id 610: end
Search this node’s immediate children using CSS selector selector
# File lib/nokogiri/xml/node.rb, line 194 194: def > selector 195: ns = document.root.namespaces 196: xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first 197: end
Get the attribute value for the attribute name
# File lib/nokogiri/xml/node.rb, line 228 228: def [] name 229: return nil unless key?(name.to_s) 230: get(name.to_s) 231: end
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 a visitor. This method calls “visit” on visitor with self.
# File lib/nokogiri/xml/node.rb, line 600 600: def accept visitor 601: visitor.visit(self) 602: end
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 new child node.
# File lib/nokogiri/xml/node.rb, line 238 238: def add_child node_or_tags 239: node_or_tags = coerce(node_or_tags) 240: if node_or_tags.is_a?(XML::NodeSet) 241: node_or_tags.each { |n| add_child_node n } 242: else 243: add_child_node node_or_tags 244: end 245: end
Adds a namespace definition with prefix using href
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); }
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 new sibling node.
Also see related method after.
# File lib/nokogiri/xml/node.rb, line 270 270: def add_next_sibling node_or_tags 271: node_or_tags = coerce(node_or_tags) 272: if node_or_tags.is_a?(XML::NodeSet) 273: if '1.8.6' == RUBY_VERSION 274: node_or_tags.reverse.each { |n| add_next_sibling_node n } 275: else 276: node_or_tags.reverse_each { |n| add_next_sibling_node n } 277: end 278: else 279: add_next_sibling_node node_or_tags 280: end 281: end
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 new sibling node.
Also see related method before.
# File lib/nokogiri/xml/node.rb, line 254 254: def add_previous_sibling node_or_tags 255: node_or_tags = coerce(node_or_tags) 256: if node_or_tags.is_a?(XML::NodeSet) 257: node_or_tags.each { |n| add_previous_sibling_node n } 258: else 259: add_previous_sibling_node node_or_tags 260: end 261: end
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.
# File lib/nokogiri/xml/node.rb, line 302 302: def after node_or_tags 303: add_next_sibling node_or_tags 304: self 305: end
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 549 549: def ancestors selector = nil 550: return NodeSet.new(document) unless respond_to?(:parent) 551: return NodeSet.new(document) unless parent 552: 553: parents = [parent] 554: 555: while parents.last.respond_to?(:parent) 556: break unless ctx_parent = parents.last.parent 557: parents << ctx_parent 558: end 559: 560: return NodeSet.new(document, parents) unless selector 561: 562: root = parents.last 563: 564: NodeSet.new(document, parents.find_all { |parent| 565: root.search(selector).include?(parent) 566: }) 567: end
Search for the first occurrence of path.
Returns nil if nothing is found, otherwise a Node.
# File lib/nokogiri/xml/node.rb, line 203 203: def at path, ns = document.root ? document.root.namespaces : {} 204: search(path, ns).first 205: end
Search this node for the first occurrence of XPath paths. Equivalent to xpath(paths).first See Node#xpath for more information.
# File lib/nokogiri/xml/node.rb, line 213 213: def at_xpath *paths 214: xpath(*paths).first 215: end
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); }
returns a list containing the Node attributes.
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 ; }
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), NIL_P(namespace) ? NULL : (xmlChar *)StringValuePtr(namespace)); if(! prop) return Qnil; return Nokogiri_wrap_xml_node(Qnil, (xmlNodePtr)prop); }
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 # instead.
# File lib/nokogiri/xml/node.rb, line 382 382: def attributes 383: Hash[*(attribute_nodes.map { |node| 384: [node.node_name, node] 385: }.flatten)] 386: end
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.
# File lib/nokogiri/xml/node.rb, line 290 290: def before node_or_tags 291: add_previous_sibling node_or_tags 292: self 293: end
Is this node blank?
static VALUE blank_eh(VALUE self) { xmlNodePtr node; Data_Get_Struct(self, xmlNode, node); return (1 == xmlIsBlankNode(node)) ? Qtrue : Qfalse ; }
Returns true if this is a CDATA
# File lib/nokogiri/xml/node.rb, line 482 482: def cdata? 483: type == CDATA_SECTION_NODE 484: end
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); }
Get the list of children for this node as a NodeSet
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; }
Returns the content for this Node
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; }
Create an external subset
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 an internal subset
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); }
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 176 176: def css *rules 177: # Pop off our custom function handler if it exists 178: handler = ![ 179: Hash, String, Symbol 180: ].include?(rules.last.class) ? rules.pop : nil 181: 182: ns = rules.last.is_a?(Hash) ? rules.pop : 183: (document.root ? document.root.namespaces : {}) 184: 185: rules = rules.map { |rule| 186: CSS.xpath_for(rule, :prefix => ".//", :ns => ns) 187: }.flatten.uniq + [ns, handler].compact 188: 189: xpath(*rules) 190: end
Get the path to this node as a CSS expression
# File lib/nokogiri/xml/node.rb, line 540 540: def css_path 541: path.split(/\//).map { |part| 542: part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)') 543: }.compact.join(' > ') 544: end
Decorate this node with the decorators set up in this node’s Document
# File lib/nokogiri/xml/node.rb, line 89 89: def decorate! 90: document.decorate(self) 91: end
Set the default namespace for this node to url
# File lib/nokogiri/xml/node.rb, line 571 571: def default_namespace= url 572: add_namespace_definition(nil, url) 573: end
Fetch the Nokogiri::HTML::ElementDescription for this node. Returns nil on XML documents and on unknown tags.
# File lib/nokogiri/xml/node.rb, line 509 509: def description 510: return nil if document.xml? 511: Nokogiri::HTML::ElementDescription[name] 512: end
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); }
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; 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; return Nokogiri_wrap_xml_node(rb_obj_class(self), dup); }
Iterate over each attribute name and value pair for this Node.
# File lib/nokogiri/xml/node.rb, line 402 402: def each &block 403: attribute_nodes.each { |node| 404: block.call([node.node_name, node.value]) 405: } 406: end
Returns true if this is an Element node
# File lib/nokogiri/xml/node.rb, line 522 522: def element? 523: type == ELEMENT_NODE 524: end
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
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 any special characters in string
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; }
Get the external subset
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); }
Returns the first child node of this node that is an element.
Example:
@doc.root.first_element_child.element? # => true
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); }
Create a DocumentFragment containing tags that is relative to this context node.
# File lib/nokogiri/xml/node.rb, line 424 424: def fragment tags 425: type = document.html? ? Nokogiri::HTML : Nokogiri::XML 426: type::DocumentFragment.new(document, tags, self) 427: end
Returns true if this is a DocumentFragment
# File lib/nokogiri/xml/node.rb, line 502 502: def fragment? 503: type == DOCUMENT_FRAG_NODE 504: end
Returns true if this is an HTML::Document node
# File lib/nokogiri/xml/node.rb, line 492 492: def html? 493: type == HTML_DOCUMENT_NODE 494: end
Get the inner_html for this node’s Node#children
# File lib/nokogiri/xml/node.rb, line 535 535: def inner_html *args 536: children.map { |x| x.to_html(*args) }.join 537: end
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.
# File lib/nokogiri/xml/node.rb, line 312 312: def inner_html= node_or_tags 313: node_or_tags = coerce(node_or_tags) 314: children.unlink 315: if node_or_tags.is_a?(XML::NodeSet) 316: node_or_tags.each { |n| add_child_node n } 317: else 318: add_child node_or_tags 319: end 320: self 321: end
Get the internal subset
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); }
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; }
Get the attribute names for this Node.
# File lib/nokogiri/xml/node.rb, line 396 396: def keys 397: attribute_nodes.map { |node| node.node_name } 398: end
Returns the last child node of this node that is an element.
Example:
@doc.root.last_element_child.element? # => true
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); }
Returns the line for this Node
static VALUE line(VALUE self) { xmlNodePtr node; Data_Get_Struct(self, xmlNode, node); return INT2NUM(xmlGetLineNo(node)); }
Returns true if this Node matches selector
# File lib/nokogiri/xml/node.rb, line 417 417: def matches? selector 418: ancestors.last.search(selector).include?(self) 419: end
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 ; }
Set the namespace for this node to ns
# File lib/nokogiri/xml/node.rb, line 578 578: def namespace= ns 579: return set_namespace(ns) unless ns 580: 581: unless Nokogiri::XML::Namespace === ns 582: raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace" 583: end 584: if ns.document != document 585: raise ArgumentError, 'namespace must be declared on the same document' 586: end 587: 588: set_namespace ns 589: end
returns a list of Namespace nodes defined on self
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; }
returns a list of Namespace nodes in scope for self. this is all namespaces defined in the node, or in any ancestor node.
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; }
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), NIL_P(namespace) ? NULL : (xmlChar *)StringValuePtr(namespace))) return Qtrue; return Qfalse; }
Get a hash containing the Namespace definitions for this Node
# File lib/nokogiri/xml/node.rb, line 463 463: def namespaces 464: Hash[*namespace_scopes.map { |nd| 465: key = ['xmlns', nd.prefix].compact.join(':') 466: if RUBY_VERSION >= '1.9' && document.encoding 467: begin 468: key.force_encoding document.encoding 469: rescue ArgumentError 470: end 471: end 472: [key, nd.href] 473: }.flatten] 474: end
Returns the next Nokogiri::XML::Element type sibling node.
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); }
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) ; }
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); return Qnil; }
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; }
Get the type for this Node
static VALUE node_type(VALUE self) { xmlNodePtr node; Data_Get_Struct(self, xmlNode, node); return INT2NUM((long)node->type); }
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.
# File lib/nokogiri/xml/node.rb, line 433 433: def parse string_or_io, options = ParseOptions::DEFAULT_XML 434: if Fixnum === options 435: options = Nokogiri::XML::ParseOptions.new(options) 436: end 437: # Give the options to the user 438: yield options if block_given? 439: 440: contents = string_or_io.respond_to?(:read) ? 441: string_or_io.read : 442: string_or_io 443: 444: return Nokogiri::XML::NodeSet.new(document) if contents.empty? 445: in_context(contents, options.to_i) 446: end
Returns the path associated with this Node
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 ; }
Get the internal pointer number
static VALUE pointer_id(VALUE self) { xmlNodePtr node; Data_Get_Struct(self, xmlNode, node); return INT2NUM((long)(node)); }
Returns the previous Nokogiri::XML::Element type sibling node.
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 ; }
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); }
Is this a read only node?
# File lib/nokogiri/xml/node.rb, line 516 516: def read_only? 517: # According to gdome2, these are read-only node types 518: [NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type) 519: end
Remove the attribute named name
# File lib/nokogiri/xml/node.rb, line 410 410: def remove_attribute name 411: attributes[name].remove if key? name 412: end
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 new child node.
Also see related method swap.
# File lib/nokogiri/xml/node.rb, line 330 330: def replace node_or_tags 331: node_or_tags = coerce(node_or_tags) 332: if node_or_tags.is_a?(XML::NodeSet) 333: node_or_tags.each { |n| add_previous_sibling n } 334: unlink 335: else 336: replace_node node_or_tags 337: end 338: end
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 97 97: def search *paths 98: ns = paths.last.is_a?(Hash) ? paths.pop : 99: (document.root ? document.root.namespaces : {}) 100: xpath(*(paths.map { |path| 101: path = path.to_s 102: path =~ /^(\.\/|\/)/ ? path : CSS.xpath_for( 103: path, 104: :prefix => ".//", 105: :ns => ns 106: ) 107: }.flatten.uniq) + [ns]) 108: end
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 626 626: def serialize *args, &block 627: options = args.first.is_a?(Hash) ? args.shift : { 628: :encoding => args[0], 629: :save_with => args[1] || SaveOptions::FORMAT 630: } 631: 632: encoding = options[:encoding] || document.encoding 633: 634: outstring = "" 635: if encoding && outstring.respond_to?(:force_encoding) 636: outstring.force_encoding(Encoding.find(encoding)) 637: end 638: io = StringIO.new(outstring) 639: write_to io, options, &block 640: io.string 641: end
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.
# File lib/nokogiri/xml/node.rb, line 347 347: def swap node_or_tags 348: replace node_or_tags 349: self 350: end
Returns true if this is a Text node
# File lib/nokogiri/xml/node.rb, line 497 497: def text? 498: type == TEXT_NODE 499: end
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 650 650: def to_html options = {} 651: # FIXME: this is a hack around broken libxml versions 652: return dump_html if ]2 6] === LIBXML_VERSION.split('.')[0..1] 653: 654: options[:save_with] ||= SaveOptions::FORMAT | 655: SaveOptions::NO_DECLARATION | 656: SaveOptions::NO_EMPTY_TAGS | 657: SaveOptions::AS_HTML 658: 659: serialize(options) 660: end
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 680 680: def to_xhtml options = {} 681: # FIXME: this is a hack around broken libxml versions 682: return dump_html if ]2 6] === LIBXML_VERSION.split('.')[0..1] 683: 684: options[:save_with] ||= SaveOptions::FORMAT | 685: SaveOptions::NO_DECLARATION | 686: SaveOptions::NO_EMPTY_TAGS | 687: SaveOptions::AS_XHTML 688: 689: serialize(options) 690: end
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 668 668: def to_xml options = {} 669: options[:save_with] ||= SaveOptions::FORMAT | SaveOptions::AS_XML 670: 671: serialize(options) 672: end
Yields self and all children to block recursively.
# File lib/nokogiri/xml/node.rb, line 593 593: def traverse &block 594: children.each{|j| j.traverse(&block) } 595: block.call(self) 596: end
Unlink this node from its current context.
static VALUE unlink_node(VALUE self) { xmlNodePtr node; Data_Get_Struct(self, xmlNode, node); xmlUnlinkNode(node); NOKOGIRI_ROOT_NODE(node); return self; }
Get the attribute values for this Node.
# File lib/nokogiri/xml/node.rb, line 390 390: def values 391: attribute_nodes.map { |node| node.value } 392: end
Write Node as HTML to io with options
See Node#write_to for a list of options
# File lib/nokogiri/xml/node.rb, line 727 727: def write_html_to io, options = {} 728: # FIXME: this is a hack around broken libxml versions 729: return (io << dump_html) if ]2 6] === LIBXML_VERSION.split('.')[0..1] 730: 731: options[:save_with] ||= SaveOptions::FORMAT | 732: SaveOptions::NO_DECLARATION | 733: SaveOptions::NO_EMPTY_TAGS | 734: SaveOptions::AS_HTML 735: write_to io, options 736: end
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 709 709: def write_to io, *options 710: options = options.first.is_a?(Hash) ? options.shift : {} 711: encoding = options[:encoding] || options[0] 712: save_options = options[:save_with] || options[1] || SaveOptions::FORMAT 713: indent_text = options[:indent_text] || ' ' 714: indent_times = options[:indent] || 2 715: 716: 717: config = SaveOptions.new(save_options) 718: yield config if block_given? 719: 720: native_write_to(io, encoding, indent_text * indent_times, config.options) 721: end
Write Node as XHTML to io with options
See Node#write_to for a list of options
# File lib/nokogiri/xml/node.rb, line 742 742: def write_xhtml_to io, options = {} 743: # FIXME: this is a hack around broken libxml versions 744: return (io << dump_html) if ]2 6] === LIBXML_VERSION.split('.')[0..1] 745: 746: options[:save_with] ||= SaveOptions::FORMAT | 747: SaveOptions::NO_DECLARATION | 748: SaveOptions::NO_EMPTY_TAGS | 749: SaveOptions::AS_XHTML 750: write_to io, options 751: end
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 759 759: def write_xml_to io, options = {} 760: options[:save_with] ||= SaveOptions::FORMAT | SaveOptions::AS_XML 761: write_to io, options 762: end
Returns true if this is an XML::Document node
# File lib/nokogiri/xml/node.rb, line 487 487: def xml? 488: type == DOCUMENT_NODE 489: end
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 129 129: def xpath *paths 130: # Pop off our custom function handler if it exists 131: handler = ![ 132: Hash, String, Symbol 133: ].include?(paths.last.class) ? paths.pop : nil 134: 135: ns = paths.last.is_a?(Hash) ? paths.pop : 136: (document.root ? document.root.namespaces : {}) 137: 138: return NodeSet.new(document) unless document 139: 140: sets = paths.map { |path| 141: ctx = XPathContext.new(self) 142: ctx.register_namespaces(ns) 143: ctx.evaluate(path, handler) 144: } 145: return sets.first if sets.length == 1 146: 147: NodeSet.new(document) do |combined| 148: sets.each do |set| 149: set.each do |node| 150: combined << node 151: end 152: end 153: end 154: end
Returns the Node as html.
static VALUE dump_html(VALUE self) { xmlBufferPtr buf ; xmlNodePtr node ; VALUE html; Data_Get_Struct(self, xmlNode, node); buf = xmlBufferCreate() ; htmlNodeDump(buf, node->doc, node); html = NOKOGIRI_STR_NEW2(buf->content); xmlBufferFree(buf); return html ; }
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(NIL_P(attribute)) return Qnil; propstr = xmlGetProp(node, (xmlChar *)StringValuePtr(attribute)); if(!propstr) return Qnil; rval = NOKOGIRI_STR_NEW2(propstr); xmlFree(propstr); return rval ; }
TODO: DOCUMENT ME
static VALUE in_context(VALUE self, VALUE _str, VALUE _options) { xmlNodePtr node; xmlNodePtr list; xmlNodeSetPtr set; xmlParserErrors error; VALUE doc, err; Data_Get_Struct(self, xmlNode, node); doc = DOC_RUBY_OBJECT(node->doc); err = rb_iv_get(doc, "@errors"); xmlSetStructuredErrorFunc((void *)err, Nokogiri_error_array_pusher); /* Twiddle global variable because of a bug in libxml2. * http://git.gnome.org/browse/libxml2/commit/?id=e20fb5a72c83cbfc8e4a8aa3943c6be8febadab7 */ #ifndef HTML_PARSE_NOIMPLIED htmlHandleOmittedElem(0); #endif error = xmlParseInNodeContext( node, StringValuePtr(_str), (int)RSTRING_LEN(_str), (int)NUM2INT(_options), &list); #ifndef HTML_PARSE_NOIMPLIED htmlHandleOmittedElem(1); #endif xmlSetStructuredErrorFunc(NULL, NULL); /* FIXME: This probably needs to handle more constants... */ switch(error) { case XML_ERR_OK: break; case XML_ERR_INTERNAL_ERROR: case XML_ERR_NO_MEMORY: rb_raise(rb_eRuntimeError, "error parsing fragment (%d)", error); break; default: break; } set = xmlXPathNodeSetCreate(NULL); while(list) { xmlXPathNodeSetAddUnique(set, list); list = list->next; } return Nokogiri_wrap_xml_node_set(set, doc); }
# File lib/nokogiri/xml/node.rb, line 790 790: def inspect_attributes 791: [:name, :namespace, :attribute_nodes, :children] 792: end
Set the content for this Node
static VALUE set_content(VALUE self, VALUE content) { xmlNodePtr node, child, next ; Data_Get_Struct(self, xmlNode, node); child = node->children; while (NULL != child) { next = child->next ; xmlUnlinkNode(child) ; NOKOGIRI_ROOT_NODE(child) ; child = next ; } xmlNodeSetContent(node, (xmlChar *)StringValuePtr(content)); return content; }
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 the namespace to namespace
static VALUE set_namespace(VALUE self, VALUE namespace) { xmlNodePtr node; xmlNsPtr ns = NULL; Data_Get_Struct(self, xmlNode, node); if(!NIL_P(namespace)) Data_Get_Struct(namespace, xmlNs, ns); xmlSetNs(node, ns); return self; }
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.
Returns true if this is a Comment