Class: Nokogiri::XML::Node
- Inherits:
-
Object
- Object
- Nokogiri::XML::Node
- Includes:
- PP::Node
- Defined in:
- lib/nokogiri/xml/node.rb,
lib/nokogiri/ffi/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
Direct Known Subclasses
Attr, AttributeDecl, CharacterData, DTD, Document, DocumentFragment, Element, ElementDecl, EntityDecl, EntityReference, ProcessingInstruction
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
Instance Attribute Summary collapse
-
#cstruct ⇒ Object
:stopdoc:.
Class Method Summary collapse
-
.new(name, document) ⇒ Object
Create a new node with
name
sharing GC lifecycle withdocument
. - .node_properties(cstruct) ⇒ Object
- .wrap(node_struct, klass = nil) ⇒ Object
Instance Method Summary collapse
- #<< ⇒ Object
-
#<=>(other) ⇒ Object
Compare two Node objects with respect to their Document.
-
#==(other) ⇒ Object
Test to see if this Node is equal to
other
. -
#[](name) ⇒ Object
(also: #get_attribute)
Get the attribute value for the attribute
name
. -
#[]=(property, value) ⇒ Object
Set the
property
tovalue
. -
#accept(visitor) ⇒ Object
Accept a visitor.
-
#add_child(node) ⇒ Object
Add
node
as a child of this node. - #add_namespace ⇒ Object
-
#add_namespace_definition(prefix, href) ⇒ Object
Adds a namespace definition with
prefix
usinghref
. -
#add_next_sibling(node) ⇒ Object
Insert
node
after this node (as a sibling). -
#add_previous_sibling(node) ⇒ Object
Insert
node
before this node (as a sibling). -
#after(data) ⇒ Object
Create nodes from
data
and insert them after this node (as a sibling). -
#ancestors(selector = nil) ⇒ Object
Get a list of ancestor Node for this Node.
-
#at(path, ns = document.root ? document.root.namespaces : {}) ⇒ Object
(also: #%)
Search for the first occurrence of
path
. -
#at_css(*rules) ⇒ Object
Search this node for the first occurrence of CSS
rules
. -
#at_xpath(*paths) ⇒ Object
Search this node for the first occurrence of XPath
paths
. -
#attribute(name) ⇒ Object
Get the attribute node with
name
. -
#attribute_nodes ⇒ Object
returns a list containing the Node attributes.
-
#attribute_with_ns(name, namespace) ⇒ Object
Get the attribute node with
name
andnamespace
. -
#attributes ⇒ Object
Returns a hash containing the node’s attributes.
-
#before(data) ⇒ Object
Create nodes from
data
and insert them before this node (as a sibling). -
#blank? ⇒ Boolean
Is this node blank?.
-
#cdata? ⇒ Boolean
Returns true if this is a CDATA.
-
#child ⇒ Object
Returns the child node.
-
#children ⇒ Object
Get the list of children for this node as a NodeSet.
- #clone ⇒ Object
-
#comment? ⇒ Boolean
Returns true if this is a Comment.
-
#content ⇒ Object
Returns the content for this Node.
-
#content=(string) ⇒ Object
Set the Node content to
string
. -
#create_external_subset(name, external_id, system_id) ⇒ Object
Create an external subset.
-
#create_internal_subset(name, external_id, system_id) ⇒ Object
Create an internal subset.
-
#css(*rules) ⇒ Object
Search this node for CSS
rules
. -
#css_path ⇒ Object
Get the path to this node as a CSS expression.
-
#decorate! ⇒ Object
Decorate this node with the decorators set up in this node’s Document.
-
#default_namespace=(url) ⇒ Object
Set the default namespace for this node to
url
. -
#description ⇒ Object
Fetch the Nokogiri::HTML::ElementDescription for this node.
-
#document ⇒ Object
Get the document for this Node.
-
#dup ⇒ Object
Copy this node.
-
#each(&block) ⇒ Object
Iterate over each attribute name and value pair for this Node.
-
#element? ⇒ Boolean
(also: #elem?)
Returns true if this is an Element node.
-
#encode_special_chars(string) ⇒ Object
Encode any special characters in
string
. -
#external_subset ⇒ Object
Get the external subset.
-
#fragment(tags) ⇒ Object
:nodoc:.
- #has_attribute? ⇒ Object
-
#html? ⇒ Boolean
Returns true if this is an HTML::Document node.
-
#initialize(name, document) ⇒ Node
constructor
A new instance of Node.
-
#inner_html(*args) ⇒ Object
Get the inner_html for this node’s Node#children.
-
#inner_html=(tags) ⇒ Object
Set the inner_html for this Node to
tags
. - #inner_text ⇒ Object
-
#internal_subset ⇒ Object
Get the internal subset.
-
#key?(attribute) ⇒ Boolean
Returns true if
attribute
is set. -
#keys ⇒ Object
Get the attribute names for this Node.
-
#line ⇒ Object
Returns the line for this Node.
-
#matches?(selector) ⇒ Boolean
Returns true if this Node matches
selector
. - #name ⇒ Object
- #name= ⇒ Object
-
#namespace ⇒ Object
returns the Nokogiri::XML::Namespace for the node, if one exists.
-
#namespace=(ns) ⇒ Object
Set the namespace for this node to
ns
. -
#namespace_definitions ⇒ Object
returns a list of Namespace nodes defined on self.
-
#namespaced_key?(attribute, namespace) ⇒ Boolean
Returns true if
attribute
is set withnamespace
. -
#namespaces ⇒ Object
Get a hash containing the Namespace definitions for this Node.
- #next ⇒ Object
-
#next_sibling ⇒ Object
Returns the next sibling node.
-
#name ⇒ Object
Returns the name for this Node.
-
#name=(new_name) ⇒ Object
Set the name for this Node.
-
#node_type ⇒ Object
Get the type for this Node.
-
#parent ⇒ Object
Get the parent Node for this Node.
-
#parent=(parent_node) ⇒ Object
Set the parent Node for this Node.
-
#path ⇒ Object
Returns the path associated with this Node.
-
#pointer_id ⇒ Object
Get the internal pointer number.
- #previous ⇒ Object
-
#previous_sibling ⇒ Object
Returns the previous sibling node.
-
#read_only? ⇒ Boolean
Is this a read only node?.
- #remove ⇒ Object
-
#remove_attribute(name) ⇒ Object
(also: #delete)
Remove the attribute named
name
. -
#replace(new_node) ⇒ Object
replace
this Node with thenew_node
in the Document. -
#search(*paths) ⇒ Object
(also: #/)
Search this node for
paths
. -
#serialize(*args, &block) ⇒ Object
Serialize Node using
options
. - #set_attribute ⇒ Object
-
#swap(data) ⇒ Object
Swap this Node for new nodes made from
data
. - #text ⇒ Object (also: #to_str)
-
#text? ⇒ Boolean
Returns true if this is a Text node.
-
#to_html(options = {}) ⇒ Object
Serialize this Node to HTML.
-
#to_s ⇒ Object
Turn this node in to a string.
-
#to_xhtml(options = {}) ⇒ Object
Serialize this Node to XHTML using
options
. -
#to_xml(options = {}) ⇒ Object
Serialize this Node to XML using
options
. -
#traverse(&block) ⇒ Object
Yields self and all children to
block
recursively. - #type ⇒ Object
-
#unlink ⇒ Object
Unlink this node from its current context.
-
#values ⇒ Object
Get the attribute values for this Node.
-
#write_html_to(io, options = {}) ⇒ Object
Write Node as HTML to
io
withoptions
. -
#write_to(io, *options) {|config| ... } ⇒ Object
Write Node to
io
withoptions
. -
#write_xhtml_to(io, options = {}) ⇒ Object
Write Node as XHTML to
io
withoptions
. -
#write_xml_to(io, options = {}) ⇒ Object
Write Node as XML to
io
withoptions
. -
#xml? ⇒ Boolean
Returns true if this is an XML::Document node.
-
#xpath(*paths) ⇒ Object
Search this node for XPath
paths
.
Methods included from PP::Node
Constructor Details
#initialize(name, document) ⇒ Node
Returns a new instance of Node.
82 83 84 |
# File 'lib/nokogiri/xml/node.rb', line 82 def initialize name, document # ... Ya. This is empty on purpose. end |
Instance Attribute Details
#cstruct ⇒ Object
:stopdoc:
6 7 8 |
# File 'lib/nokogiri/ffi/xml/node.rb', line 6 def cstruct @cstruct end |
Class Method Details
.new(name, document) ⇒ Object
Create a new node with name
sharing GC lifecycle with document
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 |
# File 'ext/nokogiri/xml_node.c', line 856 def self.new(name, doc, *rest) ptr = LibXML.xmlNewNode(nil, name.to_s) node_cstruct = LibXML::XmlNode.new(ptr) node_cstruct[:doc] = doc.cstruct[:doc] node_cstruct.keep_reference_from_document! node = Node.wrap( node_cstruct, Node == self ? nil : self ) node.send :initialize, name, doc, *rest yield node if block_given? node end |
.node_properties(cstruct) ⇒ Object
333 334 335 336 337 338 339 340 341 342 |
# File 'lib/nokogiri/ffi/xml/node.rb', line 333 def node_properties(cstruct) attr = [] prop_cstruct = cstruct[:properties] while ! prop_cstruct.null? prop = Node.wrap(prop_cstruct) attr << prop prop_cstruct = prop.cstruct[:next] end attr end |
.wrap(node_struct, klass = nil) ⇒ Object
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 |
# File 'lib/nokogiri/ffi/xml/node.rb', line 275 def self.wrap(node_struct, klass=nil) if node_struct.is_a?(FFI::Pointer) # cast native pointers up into a node cstruct return nil if node_struct.null? node_struct = LibXML::XmlNode.new(node_struct) end raise "wrapping a node without a document" unless node_struct.document document_struct = node_struct.document document_obj = document_struct.nil? ? nil : document_struct.ruby_doc if node_struct[:type] == DOCUMENT_NODE || node_struct[:type] == HTML_DOCUMENT_NODE return document_obj end ruby_node = node_struct.ruby_node return ruby_node unless ruby_node.nil? klasses = case node_struct[:type] when ELEMENT_NODE then [XML::Element] when TEXT_NODE then [XML::Text] when ENTITY_REF_NODE then [XML::EntityReference] when ATTRIBUTE_DECL then [XML::AttributeDecl, LibXML::XmlAttribute] when ELEMENT_DECL then [XML::ElementDecl, LibXML::XmlElement] when COMMENT_NODE then [XML::Comment] when DOCUMENT_FRAG_NODE then [XML::DocumentFragment] when PI_NODE then [XML::ProcessingInstruction] when ATTRIBUTE_NODE then [XML::Attr] when ENTITY_DECL then [XML::EntityDecl, LibXML::XmlEntity] when CDATA_SECTION_NODE then [XML::CDATA] when DTD_NODE then [XML::DTD, LibXML::XmlDtd] else [XML::Node] end if klass node = klass.allocate else node = klasses.first.allocate end node.cstruct = klasses[1] ? klasses[1].new(node_struct.pointer) : node_struct node.cstruct.ruby_node = node if document_obj node.instance_variable_set(:@document, document_obj) cache = document_obj.instance_variable_get(:@node_cache) cache << node document_obj.decorate(node) end node end |
Instance Method Details
#<< ⇒ Object
236 |
# File 'lib/nokogiri/xml/node.rb', line 236 alias :<< :add_child |
#<=>(other) ⇒ Object
Compare two Node objects with respect to their Document. Nodes from different documents cannot be compared.
653 654 655 656 657 |
# File 'lib/nokogiri/xml/node.rb', line 653 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
490 491 492 493 494 |
# File 'lib/nokogiri/xml/node.rb', line 490 def == other return false unless other return false unless other.respond_to?(:pointer_id) pointer_id == other.pointer_id end |
#[](name) ⇒ Object Also known as: get_attribute
Get the attribute value for the attribute name
223 224 225 226 |
# File 'lib/nokogiri/xml/node.rb', line 223 def [] name return nil unless key?(name.to_s) get(name.to_s) end |
#[]=(property, value) ⇒ Object
Set the property
to value
469 470 471 472 |
# File 'ext/nokogiri/xml_node.c', line 469 def []=(property, value) LibXML.xmlSetProp(cstruct, property, value) value end |
#accept(visitor) ⇒ Object
Accept a visitor. This method calls “visit” on visitor
with self.
471 472 473 |
# File 'lib/nokogiri/xml/node.rb', line 471 def accept visitor visitor.visit(self) end |
#add_child(node) ⇒ Object
Add node
as a child of this node. Returns the new child node.
676 677 678 679 680 |
# File 'ext/nokogiri/xml_node.c', line 676 def add_child(child) Node.reparent_node_with(child, self) do |child_cstruct, my_cstruct| LibXML.xmlAddChild(my_cstruct, child_cstruct) end end |
#add_namespace ⇒ Object
448 |
# File 'lib/nokogiri/xml/node.rb', line 448 alias :add_namespace :add_namespace_definition |
#add_namespace_definition(prefix, href) ⇒ Object
Adds a namespace definition with prefix
using href
825 826 827 828 829 830 831 832 833 |
# File 'ext/nokogiri/xml_node.c', line 825 def add_namespace_definition(prefix, href) ns = LibXML.xmlNewNs(cstruct, href, prefix) if ns.null? ns = LibXML.xmlSearchNs(cstruct.document, cstruct, prefix.nil? ? nil : prefix.to_s) end LibXML.xmlSetNs(cstruct, ns) if prefix.nil? Namespace.wrap(cstruct.document, ns) end |
#add_next_sibling(node) ⇒ Object
Insert node
after this node (as a sibling).
751 752 753 754 755 |
# File 'ext/nokogiri/xml_node.c', line 751 def add_next_sibling(next_sibling) Node.reparent_node_with(next_sibling, self) do |sibling_cstruct, my_cstruct| LibXML.xmlAddNextSibling(my_cstruct, sibling_cstruct) end end |
#add_previous_sibling(node) ⇒ Object
Insert node
before this node (as a sibling).
762 763 764 765 766 |
# File 'ext/nokogiri/xml_node.c', line 762 def add_previous_sibling(prev_sibling) Node.reparent_node_with(prev_sibling, self) do |sibling_cstruct, my_cstruct| LibXML.xmlAddPrevSibling(my_cstruct, sibling_cstruct) end end |
#after(data) ⇒ Object
Create nodes from data
and insert them after this node (as a sibling).
298 299 300 301 302 303 |
# File 'lib/nokogiri/xml/node.rb', line 298 def after data fragment(data).children.to_a.reverse.each do |node| add_next_sibling node end self end |
#ancestors(selector = nil) ⇒ Object
Get a list of ancestor Node for this Node. If selector
is given, the ancestors must match selector
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 |
# File 'lib/nokogiri/xml/node.rb', line 425 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 : {}) ⇒ Object Also known as: %
Search for the first occurrence of path
. Returns nil if nothing is found, otherwise a Node.
198 199 200 |
# File 'lib/nokogiri/xml/node.rb', line 198 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.
217 218 219 |
# File 'lib/nokogiri/xml/node.rb', line 217 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.
208 209 210 |
# File 'lib/nokogiri/xml/node.rb', line 208 def at_xpath *paths xpath(*paths).first end |
#attribute(name) ⇒ Object
Get the attribute node with name
530 531 532 |
# File 'ext/nokogiri/xml_node.c', line 530 def attribute(name) attribute_nodes.find { |x| x.name == name } end |
#attribute_nodes ⇒ Object
returns a list containing the Node attributes.
565 566 567 |
# File 'ext/nokogiri/xml_node.c', line 565 def attribute_nodes Node.node_properties cstruct end |
#attribute_with_ns(name, namespace) ⇒ Object
Get the attribute node with name
and namespace
547 548 549 550 551 552 |
# File 'ext/nokogiri/xml_node.c', line 547 def attribute_with_ns(name, namespace) prop = LibXML.xmlHasNsProp(cstruct, name.to_s, namespace.nil? ? NULL : namespace.to_s) return prop if prop.null? Node.wrap(prop) end |
#attributes ⇒ Object
Returns a hash containing the node’s attributes. The key is the attribute name, the value is the string value of the attribute.
246 247 248 249 250 |
# File 'lib/nokogiri/xml/node.rb', line 246 def attributes Hash[*(attribute_nodes.map { |node| [node.node_name, node] }.flatten)] end |
#before(data) ⇒ Object
Create nodes from data
and insert them before this node (as a sibling).
288 289 290 291 292 293 |
# File 'lib/nokogiri/xml/node.rb', line 288 def before data fragment(data).children.each do |node| add_previous_sibling node end self end |
#blank? ⇒ Boolean
Is this node blank?
330 331 332 |
# File 'ext/nokogiri/xml_node.c', line 330 def blank? LibXML.xmlIsBlankNode(cstruct) == 1 end |
#cdata? ⇒ Boolean
Returns true if this is a CDATA
363 364 365 |
# File 'lib/nokogiri/xml/node.rb', line 363 def cdata? type == CDATA_SECTION_NODE end |
#child ⇒ Object
Returns the child node
421 422 423 |
# File 'ext/nokogiri/xml_node.c', line 421 def child (val = cstruct[:children]).null? ? nil : Node.wrap(val) end |
#children ⇒ Object
Get the list of children for this node as a NodeSet
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 |
# File 'ext/nokogiri/xml_node.c', line 393 def children return NodeSet.new(nil) if cstruct[:children].null? child = Node.wrap(cstruct[:children]) set = NodeSet.new child.document set_ptr = LibXML.xmlXPathNodeSetCreate(child.cstruct) set.cstruct = LibXML::XmlNodeSet.new(set_ptr) return set unless child child_ptr = child.cstruct[:next] while ! child_ptr.null? child = Node.wrap(child_ptr) LibXML.xmlXPathNodeSetAdd(set.cstruct, child.cstruct) child_ptr = child.cstruct[:next] end return set end |
#clone ⇒ Object
241 |
# File 'lib/nokogiri/xml/node.rb', line 241 alias :clone :dup |
#comment? ⇒ Boolean
Returns true if this is a Comment
358 359 360 |
# File 'lib/nokogiri/xml/node.rb', line 358 def comment? type == COMMENT_NODE end |
#content ⇒ Object
Returns the content for this Node
656 657 658 659 660 661 662 |
# File 'ext/nokogiri/xml_node.c', line 656 def content content_ptr = LibXML.xmlNodeGetContent(cstruct) return nil if content_ptr.null? content = content_ptr.read_string # TODO: encoding? LibXML.xmlFree(content_ptr) content end |
#content=(string) ⇒ Object
Set the Node content to string
. The content gets XML escaped.
331 332 333 |
# File 'lib/nokogiri/xml/node.rb', line 331 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
219 220 221 222 223 224 225 226 227 228 |
# File 'ext/nokogiri/xml_node.c', line 219 def create_external_subset name, external_id, system_id raise("Document already has an external subset") if external_subset doc = cstruct.document dtd_ptr = LibXML.xmlNewDtd doc, name, external_id, system_id return nil if dtd_ptr.null? Node.wrap dtd_ptr end |
#create_internal_subset(name, external_id, system_id) ⇒ Object
Create an internal subset
190 191 192 193 194 195 196 197 198 199 |
# File 'ext/nokogiri/xml_node.c', line 190 def create_internal_subset name, external_id, system_id raise("Document already has an internal subset") if internal_subset doc = cstruct.document dtd_ptr = LibXML.xmlCreateIntSubset doc, name, external_id, system_id return nil if dtd_ptr.null? Node.wrap dtd_ptr end |
#css(*rules) ⇒ Object
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)
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/nokogiri/xml/node.rb', line 179 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 ⇒ Object
Get the path to this node as a CSS expression
416 417 418 419 420 |
# File 'lib/nokogiri/xml/node.rb', line 416 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
88 89 90 |
# File 'lib/nokogiri/xml/node.rb', line 88 def decorate! document.decorate(self) end |
#default_namespace=(url) ⇒ Object
Set the default namespace for this node to url
445 446 447 |
# File 'lib/nokogiri/xml/node.rb', line 445 def default_namespace= url add_namespace_definition(nil, url) end |
#description ⇒ Object
Fetch the Nokogiri::HTML::ElementDescription for this node. Returns nil on XML documents and on unknown tags.
385 386 387 388 |
# File 'lib/nokogiri/xml/node.rb', line 385 def description return nil if document.xml? Nokogiri::HTML::ElementDescription[name] end |
#document ⇒ Object
Get the document for this Node
142 143 144 |
# File 'ext/nokogiri/xml_node.c', line 142 def document cstruct.document.ruby_doc end |
#dup ⇒ Object
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.
293 294 295 296 297 |
# File 'ext/nokogiri/xml_node.c', line 293 def dup(deep = 1) dup_ptr = LibXML.xmlDocCopyNode(cstruct, cstruct.document, deep) return nil if dup_ptr.null? Node.wrap(dup_ptr, self.class) end |
#each(&block) ⇒ Object
Iterate over each attribute name and value pair for this Node.
266 267 268 269 270 |
# File 'lib/nokogiri/xml/node.rb', line 266 def each &block attribute_nodes.each { |node| block.call(node.node_name, node.value) } end |
#element? ⇒ Boolean Also known as: elem?
Returns true if this is an Element node
398 399 400 |
# File 'lib/nokogiri/xml/node.rb', line 398 def element? type == ELEMENT_NODE end |
#encode_special_chars(string) ⇒ Object
Encode any special characters in string
169 170 171 172 173 174 175 |
# File 'ext/nokogiri/xml_node.c', line 169 def encode_special_chars(string) char_ptr = LibXML.xmlEncodeSpecialChars(self[:doc], string) encoded = char_ptr.read_string # TODO: encoding? LibXML.xmlFree(char_ptr) encoded end |
#external_subset ⇒ Object
Get the external subset
248 249 250 251 252 253 |
# File 'ext/nokogiri/xml_node.c', line 248 def external_subset doc = cstruct.document return nil if doc[:extSubset].null? Node.wrap(doc[:extSubset]) end |
#fragment(tags) ⇒ Object
:nodoc:
324 325 326 327 |
# File 'lib/nokogiri/xml/node.rb', line 324 def fragment # :nodoc: # TODO: deprecate? document.fragment() end |
#has_attribute? ⇒ Object
235 |
# File 'lib/nokogiri/xml/node.rb', line 235 alias :has_attribute? :key? |
#html? ⇒ Boolean
Returns true if this is an HTML::Document node
373 374 375 |
# File 'lib/nokogiri/xml/node.rb', line 373 def html? type == HTML_DOCUMENT_NODE end |
#inner_html(*args) ⇒ Object
Get the inner_html for this node’s Node#children
411 412 413 |
# File 'lib/nokogiri/xml/node.rb', line 411 def inner_html *args children.map { |x| x.to_html(*args) }.join end |
#inner_html=(tags) ⇒ Object
Set the inner_html for this Node to tags
315 316 317 318 319 320 321 322 |
# File 'lib/nokogiri/xml/node.rb', line 315 def inner_html= children.each { |x| x.remove} fragment().children.to_a.each do |node| add_child node end self end |
#inner_text ⇒ Object
234 |
# File 'lib/nokogiri/xml/node.rb', line 234 alias :inner_text :content |
#internal_subset ⇒ Object
Get the internal subset
270 271 272 273 274 275 |
# File 'ext/nokogiri/xml_node.c', line 270 def internal_subset doc = cstruct.document dtd = LibXML.xmlGetIntSubset(doc) return nil if dtd.null? Node.wrap(dtd) end |
#key?(attribute) ⇒ Boolean
Returns true if attribute
is set
438 439 440 |
# File 'ext/nokogiri/xml_node.c', line 438 def key?(attribute) ! (prop = LibXML.xmlHasProp(cstruct, attribute.to_s)).null? end |
#keys ⇒ Object
Get the attribute names for this Node.
260 261 262 |
# File 'lib/nokogiri/xml/node.rb', line 260 def keys attribute_nodes.map { |node| node.node_name } end |
#line ⇒ Object
Returns the line for this Node
811 812 813 |
# File 'ext/nokogiri/xml_node.c', line 811 def line cstruct[:line] end |
#matches?(selector) ⇒ Boolean
Returns true if this Node matches selector
281 282 283 |
# File 'lib/nokogiri/xml/node.rb', line 281 def matches? selector document.search(selector).include?(self) end |
#name ⇒ Object
237 |
# File 'lib/nokogiri/xml/node.rb', line 237 alias :name :node_name |
#name= ⇒ Object
238 |
# File 'lib/nokogiri/xml/node.rb', line 238 alias :name= :node_name= |
#namespace ⇒ Object
returns the Nokogiri::XML::Namespace for the node, if one exists.
585 586 587 |
# File 'ext/nokogiri/xml_node.c', line 585 def namespace cstruct[:ns].null? ? nil : Namespace.wrap(cstruct.document, cstruct[:ns]) end |
#namespace=(ns) ⇒ Object
Set the namespace for this node to ns
452 453 454 455 456 457 458 459 460 |
# File 'lib/nokogiri/xml/node.rb', line 452 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 ⇒ Object
returns a list of Namespace nodes defined on self
602 603 604 605 606 607 608 609 610 611 612 |
# File 'ext/nokogiri/xml_node.c', line 602 def namespace_definitions list = [] ns_ptr = cstruct[:nsDef] return list if ns_ptr.null? while ! ns_ptr.null? ns = Namespace.wrap(cstruct.document, ns_ptr) list << ns ns_ptr = ns.cstruct[:next] end list end |
#namespaced_key?(attribute, namespace) ⇒ Boolean
Returns true if attribute
is set with namespace
453 454 455 456 457 |
# File 'ext/nokogiri/xml_node.c', line 453 def namespaced_key?(attribute, namespace) prop = LibXML.xmlHasNsProp(cstruct, attribute.to_s, namespace.nil? ? nil : namespace.to_s) prop.null? ? false : true end |
#namespaces ⇒ Object
Get a hash containing the Namespace definitions for this Node
344 345 346 347 348 349 350 351 352 353 354 355 |
# File 'lib/nokogiri/xml/node.rb', line 344 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 ⇒ Object
228 |
# File 'lib/nokogiri/xml/node.rb', line 228 alias :next :next_sibling |
#next_sibling ⇒ Object
Returns the next sibling node
345 346 347 |
# File 'ext/nokogiri/xml_node.c', line 345 def next_sibling cstruct_node_from :next end |
#name ⇒ Object
Returns the name for this Node
718 719 720 |
# File 'ext/nokogiri/xml_node.c', line 718 def node_name cstruct[:name] # TODO: encoding? end |
#name=(new_name) ⇒ Object
Set the name for this Node
704 705 706 707 |
# File 'ext/nokogiri/xml_node.c', line 704 def node_name=(string) LibXML.xmlNodeSetName(cstruct, string) string end |
#node_type ⇒ Object
Get the type for this Node
629 630 631 |
# File 'ext/nokogiri/xml_node.c', line 629 def node_type cstruct[:type] end |
#parent ⇒ Object
Get the parent Node for this Node
687 688 689 |
# File 'ext/nokogiri/xml_node.c', line 687 def parent cstruct_node_from :parent end |
#parent=(parent_node) ⇒ Object
Set the parent Node for this Node
337 338 339 340 |
# File 'lib/nokogiri/xml/node.rb', line 337 def parent= parent_node parent_node.add_child(self) parent_node end |
#path ⇒ Object
Returns the path associated with this Node
733 734 735 736 737 738 |
# File 'ext/nokogiri/xml_node.c', line 733 def path path_ptr = LibXML.xmlGetNodePath(cstruct) val = path_ptr.null? ? nil : path_ptr.read_string # TODO: encoding? LibXML.xmlFree(path_ptr) val end |
#pointer_id ⇒ Object
Get the internal pointer number
155 156 157 |
# File 'ext/nokogiri/xml_node.c', line 155 def pointer_id cstruct.pointer end |
#previous ⇒ Object
229 |
# File 'lib/nokogiri/xml/node.rb', line 229 alias :previous :previous_sibling |
#previous_sibling ⇒ Object
Returns the previous sibling node
362 363 364 |
# File 'ext/nokogiri/xml_node.c', line 362 def previous_sibling cstruct_node_from :prev end |
#read_only? ⇒ Boolean
Is this a read only node?
392 393 394 395 |
# File 'lib/nokogiri/xml/node.rb', line 392 def read_only? # According to gdome2, these are read-only node types [NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type) end |
#remove ⇒ Object
230 |
# File 'lib/nokogiri/xml/node.rb', line 230 alias :remove :unlink |
#remove_attribute(name) ⇒ Object Also known as: delete
Remove the attribute named name
274 275 276 |
# File 'lib/nokogiri/xml/node.rb', line 274 def remove_attribute name attributes[name].remove if key? name end |
#replace(new_node) ⇒ Object
replace
this Node with the new_node
in the Document. The new node must be a Nokogiri::XML::Node or a non-empty String
478 479 480 481 482 483 484 485 486 |
# File 'lib/nokogiri/xml/node.rb', line 478 def replace new_node if new_node.is_a?(Document) || !new_node.is_a?(XML::Node) raise ArgumentError, <<-EOERR Node.replace requires a Node argument, and cannot accept a Document. (You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().) EOERR end replace_with_node new_node 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.
96 97 98 99 100 101 102 103 104 105 106 107 |
# File 'lib/nokogiri/xml/node.rb', line 96 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 |
#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
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 |
# File 'lib/nokogiri/xml/node.rb', line 510 def serialize *args, &block = args.first.is_a?(Hash) ? args.shift : { :encoding => args[0], :save_with => args[1] || SaveOptions::FORMAT } encoding = [:encoding] || document.encoding outstring = "" if encoding && outstring.respond_to?(:force_encoding) outstring.force_encoding(Encoding.find(encoding)) end io = StringIO.new(outstring) write_to io, , &block io.string end |
#set_attribute ⇒ Object
232 |
# File 'lib/nokogiri/xml/node.rb', line 232 alias :set_attribute :[]= |
#swap(data) ⇒ Object
Swap this Node for new nodes made from data
307 308 309 310 311 |
# File 'lib/nokogiri/xml/node.rb', line 307 def swap data before(data) remove self end |
#text ⇒ Object Also known as: to_str
233 |
# File 'lib/nokogiri/xml/node.rb', line 233 alias :text :content |
#text? ⇒ Boolean
Returns true if this is a Text node
378 379 380 |
# File 'lib/nokogiri/xml/node.rb', line 378 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.
534 535 536 537 538 539 540 541 542 543 544 |
# File 'lib/nokogiri/xml/node.rb', line 534 def to_html = {} # FIXME: this is a hack around broken libxml versions return dump_html if %w[2 6] === LIBXML_VERSION.split('.')[0..1] [:save_with] ||= SaveOptions::FORMAT | SaveOptions::NO_DECLARATION | SaveOptions::NO_EMPTY_TAGS | SaveOptions::AS_HTML serialize() end |
#to_s ⇒ Object
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.
406 407 408 |
# File 'lib/nokogiri/xml/node.rb', line 406 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
566 567 568 569 570 571 572 573 574 575 576 |
# File 'lib/nokogiri/xml/node.rb', line 566 def to_xhtml = {} # FIXME: this is a hack around broken libxml versions return dump_html if %w[2 6] === LIBXML_VERSION.split('.')[0..1] [:save_with] ||= SaveOptions::FORMAT | SaveOptions::NO_DECLARATION | SaveOptions::NO_EMPTY_TAGS | SaveOptions::AS_XHTML serialize() 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
552 553 554 555 556 557 558 |
# File 'lib/nokogiri/xml/node.rb', line 552 def to_xml = {} encoding = nil [:save_with] ||= SaveOptions::FORMAT | SaveOptions::AS_XML serialize() end |
#traverse(&block) ⇒ Object
Yields self and all children to block
recursively.
464 465 466 467 |
# File 'lib/nokogiri/xml/node.rb', line 464 def traverse &block children.each{|j| j.traverse(&block) } block.call(self) end |
#type ⇒ Object
239 |
# File 'lib/nokogiri/xml/node.rb', line 239 alias :type :node_type |
#unlink ⇒ Object
Unlink this node from its current context.
315 316 317 318 319 |
# File 'ext/nokogiri/xml_node.c', line 315 def unlink LibXML.xmlUnlinkNode(cstruct) cstruct.keep_reference_from_document! self end |
#values ⇒ Object
Get the attribute values for this Node.
254 255 256 |
# File 'lib/nokogiri/xml/node.rb', line 254 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
613 614 615 616 617 618 619 620 621 622 |
# File 'lib/nokogiri/xml/node.rb', line 613 def write_html_to io, = {} # FIXME: this is a hack around broken libxml versions return (io << dump_html) if %w[2 6] === LIBXML_VERSION.split('.')[0..1] [:save_with] ||= SaveOptions::FORMAT | SaveOptions::NO_DECLARATION | SaveOptions::NO_EMPTY_TAGS | SaveOptions::AS_HTML write_to io, 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
595 596 597 598 599 600 601 602 603 604 605 606 607 |
# File 'lib/nokogiri/xml/node.rb', line 595 def write_to io, * = .first.is_a?(Hash) ? .shift : {} encoding = [:encoding] || [0] = [:save_with] || [1] || SaveOptions::FORMAT indent_text = [:indent_text] || ' ' indent_times = [:indent] || 2 config = SaveOptions.new() yield config if block_given? native_write_to(io, encoding, indent_text * indent_times, config.) end |
#write_xhtml_to(io, options = {}) ⇒ Object
Write Node as XHTML to io
with options
See Node#write_to for a list of options
628 629 630 631 632 633 634 635 636 637 |
# File 'lib/nokogiri/xml/node.rb', line 628 def write_xhtml_to io, = {} # FIXME: this is a hack around broken libxml versions return (io << dump_html) if %w[2 6] === LIBXML_VERSION.split('.')[0..1] [:save_with] ||= SaveOptions::FORMAT | SaveOptions::NO_DECLARATION | SaveOptions::NO_EMPTY_TAGS | SaveOptions::AS_XHTML write_to io, 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
645 646 647 648 |
# File 'lib/nokogiri/xml/node.rb', line 645 def write_xml_to io, = {} [:save_with] ||= SaveOptions::FORMAT | SaveOptions::AS_XML write_to io, end |
#xml? ⇒ Boolean
Returns true if this is an XML::Document node
368 369 370 |
# File 'lib/nokogiri/xml/node.rb', line 368 def xml? type == DOCUMENT_NODE end |
#xpath(*paths) ⇒ Object
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)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
# File 'lib/nokogiri/xml/node.rb', line 128 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 |