123456789_123456789_123456789_123456789_123456789_

Class: Nokogiri::XML::DocumentFragment

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Subclasses:
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Node
Instance Chain:
Inherits: Nokogiri::XML::Node
Defined in: ext/nokogiri/xml_document_fragment.c,
ext/nokogiri/xml_attr.c,
lib/nokogiri/xml/document_fragment.rb

Overview

DocumentFragment represents a DocumentFragment node in an xml document.

Constant Summary

PP::Node - Included

COLLECTIONS

Searchable - Included

LOOKS_LIKE_XPATH

::Nokogiri::ClassResolver - Included

VALID_NAMESPACES

Node - Inherited

ATTRIBUTE_DECL, ATTRIBUTE_NODE, CDATA_SECTION_NODE, COMMENT_NODE, DECONSTRUCT_KEYS, DECONSTRUCT_METHODS, DOCB_DOCUMENT_NODE, DOCUMENT_FRAG_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, DTD_NODE, ELEMENT_DECL, ELEMENT_NODE, ENTITY_DECL, ENTITY_NODE, ENTITY_REF_NODE, HTML_DOCUMENT_NODE, IMPLIED_XPATH_CONTEXTS, NAMESPACE_DECL, NOTATION_NODE, PI_NODE, TEXT_NODE, USING_LIBXML_WITH_BROKEN_SERIALIZATION, XINCLUDE_END, XINCLUDE_START

Class Method Summary

Node - Inherited

.new

documented in lib/nokogiri/xml/node.rb.

Instance Attribute Summary

Node - Inherited

#blank?
Returns

true if the node is an empty or whitespace-only text or cdata node, else false.

#cdata?

Returns true if this is a CDATA.

#children

:category: Traversing Document Structure.

#children=

Set the content for this Node node_or_tags

#comment?

Returns true if this is a Comment.

#content

[Returns].

#content=

Set the Node’s content to a Text node containing string.

#default_namespace=

Adds a default namespace supplied as a string url href, to self.

#document

:category: Traversing Document Structure.

#document?

Returns true if this is a Document.

#elem?

Alias for Node#element?.

#element?

Returns true if this is an Element node.

#fragment?

Returns true if this is a DocumentFragment.

#html?

Returns true if this is an ::Nokogiri::HTML4::Document or ::Nokogiri::HTML5::Document node.

#inner_html

Get the inner_html for this node’s Node#children

#inner_html=

Set the content for this Node to node_or_tags.

#inner_text

Alias for Node#content.

#lang

Searches the language of a node, i.e.

#lang=

Set the language of a node, i.e.

#line
Returns

The line number of this Node.

#line=

Sets the line for this Node.

#name

Alias for Node#node_name.

#namespace
Returns

The Namespace of the element or attribute node, or nil if there is no namespace.

#namespace=

Set the default namespace on this node (as would be defined with an “xmlns=” attribute in ::Nokogiri::XML source), as a Namespace object ns.

#native_content=

Set the content for this Node.

#next
#next=
#node_name

Returns the name for this Node.

#node_name=

Set the name for this Node.

#parent

Get the parent Node for this Node.

#parent=

Set the parent Node for this Node.

#previous
#previous=
#processing_instruction?

Returns true if this is a ProcessingInstruction node.

#read_only?

Is this a read only node?

#text

Alias for Node#content.

#text?

Returns true if this is a Text node.

#to_str

Alias for Node#content.

#xml?

Returns true if this is an Document node.

#prepend_newline?, #data_ptr?

Instance Method Summary

Node - Inherited

#<<

Add node_or_tags as a child of this Node.

#<=>

Compare two Node objects with respect to their Document.

#==

::Nokogiri::Test to see if this Node is equal to other

#[]

Fetch an attribute from this node.

#[]=

Update the attribute #name to value, or create the attribute if it does not exist.

#accept

Accept a visitor.

#add_child

Add node_or_tags as a child of this Node.

#add_class

Ensure HTML ::Nokogiri::CSS classes are present on self.

#add_namespace
#add_namespace_definition

:category: Manipulating Document Structure.

#add_next_sibling

Insert node_or_tags after this Node (as a sibling).

#add_previous_sibling

Insert node_or_tags before this Node (as a sibling).

#after

Insert node_or_tags after this node (as a sibling).

#ancestors

Get a list of ancestor Node for this Node.

#append_class

Add HTML ::Nokogiri::CSS classes to self, regardless of duplication.

#attr

Alias for Node#[].

#attribute

:category: Working With Node Attributes.

#attribute_nodes

:category: Working With Node Attributes.

#attribute_with_ns

:category: Working With Node Attributes.

#attributes

Fetch this node’s attributes.

#before

Insert node_or_tags before this node (as a sibling).

#canonicalize,
#child

:category: Traversing Document Structure.

#classes

Fetch CSS class names of a Node.

#clone

Clone this node.

#create_external_subset

Create an external subset.

#create_internal_subset

Create the internal subset of a document.

#css_path

Get the path to this node as a ::Nokogiri::CSS expression.

#deconstruct_keys

Returns a hash describing the Node, to use in pattern matching.

#decorate!

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

#delete
#description

Fetch the ::Nokogiri::HTML4::ElementDescription for this node.

#do_xinclude

Do xinclude substitution on the subtree below node.

#dup

Duplicate this node.

#each

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

#element_children

[Returns].

#elements
#encode_special_chars

Encode any special characters in string

#external_subset

Get the external subset.

#first_element_child
Returns

The first child Node that is an element.

#fragment

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

#get_attribute

Alias for Node#[].

#has_attribute?

Alias for Node#key?.

#initialize

Create a new node with #name that belongs to document.

#internal_subset

Get the internal subset.

#key?

Returns true if attribute is set.

#keys

Get the attribute names for this Node.

#kwattr_add

Ensure that values are present in a keyword attribute.

#kwattr_append

Add keywords to a Node’s keyword attribute, regardless of duplication.

#kwattr_remove

Remove keywords from a keyword attribute.

#kwattr_values

Fetch values from a keyword attribute of a Node.

#last_element_child
Returns

The last child Node that is an element.

#matches?

Returns true if this Node matches selector

#namespace_definitions

[Returns].

#namespace_scopes
Returns

Array of all the Namespaces on this node and its ancestors.

#namespaced_key?

Returns true if attribute is set with namespace

#namespaces

Fetch all the namespaces on this node and its ancestors.

#next_element

Returns the next Element type sibling node.

#next_sibling

Returns the next sibling node.

#node_type

Get the type for this Node.

#parse

Parse string_or_io as a document fragment within the context of this node.

#path

Returns the path associated with this Node.

#pointer_id

[Returns].

#prepend_child

Add node_or_tags as the first child of this Node.

#previous_element

Returns the previous Element type sibling node.

#previous_sibling

Returns the previous sibling node.

#remove

Alias for Node#unlink.

#remove_attribute

Remove the attribute named #name

#remove_class

Remove HTML ::Nokogiri::CSS classes from this node.

#replace

Replace this Node with node_or_tags.

#serialize

Serialize Node using options.

#set_attribute

Alias for Node#[]=.

#swap

Swap this Node for node_or_tags

#to_html

Serialize this Node to ::Nokogiri::HTML.

#to_s

Turn this node in to a string.

#to_xhtml

Serialize this Node to XHTML using options

#to_xml

Serialize this Node to ::Nokogiri::XML using options

#traverse

Yields self and all children to block recursively.

#type

Alias for Node#node_type.

#unlink

Unlink this node from its current context.

#value?

Does this Node’s attributes include <value>.

#values

Get the attribute values for this Node.

#wrap

Wrap this Node with the node parsed from markup or a dup of the node.

#write_html_to

Write Node as ::Nokogiri::HTML to io with options

#write_to

Serialize this node or document to io.

#write_xhtml_to

Write Node as XHTML to io with options

#write_xml_to

Write Node as ::Nokogiri::XML to io with options

#add_child_node_and_reparent_attrs, #add_sibling,
#compare

Compare this Node to other with respect to their Document.

#dump_html

Returns the Node as html.

#get

Get the value for attribute

#html_standard_serialize,
#in_context

TODO: DOCUMENT ME.

#inspect_attributes, #keywordify,
#native_write_to

Write this Node to io with encoding and options

#process_xincludes

Loads and substitutes all xinclude elements below the node.

#set

Set the property to value

#set_namespace

Set the namespace to namespace

#to_format, #write_format_to, #add_child_node, #add_next_sibling_node, #add_previous_sibling_node, #replace_node

::Nokogiri::ClassResolver - Included

#related_class

Find a class constant within the.

Searchable - Included

#%

Alias for Searchable#at.

#/
#>

Search this node’s immediate children using ::Nokogiri::CSS selector selector

#at

Search this object for paths, and return only the first result.

#at_css

Search this object for ::Nokogiri::CSS rules, and return only the first match.

#at_xpath

Search this node for XPath paths, and return only the first match.

#css

Search this object for ::Nokogiri::CSS rules.

#search

Search this object for paths.

#xpath

Search this node for XPath paths.

#css_internal, #css_rules_to_xpath, #xpath_impl, #xpath_internal, #xpath_query_from_css_rule, #extract_params

PP::Node - Included

Constructor Details

.new(document, name)

Alias for EntityReference.new. Create a new Attr element on the document with #name

#initialize(document, tags = nil, ctx = nil, options = ParseOptions::DEFAULT_XML) {|options| ... } ⇒ DocumentFragment

Create a new DocumentFragment from tags.

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

Yields:

  • (options)
[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 19

def initialize(document, tags = nil, ctx = nil, options = ParseOptions::DEFAULT_XML) # rubocop:disable Lint/MissingSuper
  return self unless tags

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

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

Class Method Details

.parse(tags, options = ParseOptions::DEFAULT_XML, &block)

Create a DocumentFragment from tags

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 9

def self.parse(tags, options = ParseOptions::DEFAULT_XML, &block)
  new(XML::Document.new, tags, nil, options, &block)
end

Instance Attribute Details

#errors (rw)

A list of SyntaxError found when parsing a document

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 136

def errors
  document.errors
end

#errors=(things) (rw)

This method is for internal use only.
[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 140

def errors=(things) # :nodoc:
  document.errors = things
end

Instance Method Details

#css(*rules, [namespace-bindings, custom-pseudo-class])

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

For more information see Searchable#css

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 102

def css(*args)
  if children.any?
    children.css(*args) # 'children' is a smell here
  else
    NodeSet.new(document)
  end
end

#deconstruct() → Array)

Returns the root nodes of this document fragment as an array, to use in pattern matching.

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

Example

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

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

Example only the elements, not the text nodes.

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

Since v1.14.0

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 190

def deconstruct
  children.to_a
end

#dup

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 42

def dup
  new_document = document.dup
  new_fragment = self.class.new(new_document)
  children.each do |child|
    child.dup(1, new_document).parent = new_fragment
  end
  new_fragment
end

#fragment(data)

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 144

def fragment(data)
  document.fragment(data)
end

#name

return the name for DocumentFragment

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 54

def name
  "#document-fragment"
end

#namespace_declarations(ctx) (private)

fix for issue 770

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 197

def namespace_declarations(ctx)
  ctx.namespace_scopes.map do |namespace|
    prefix = namespace.prefix.nil? ? "" : ":#{namespace.prefix}"
    %{xmlns#{prefix}="#{namespace.href}"}
  end.join(" ")
end

#search(*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])

Search this fragment for paths. paths must be one or more XPath or ::Nokogiri::CSS queries.

For more information see Searchable#search

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 121

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

  rules.inject(NodeSet.new(document)) do |set, rule|
    set + if Searchable::LOOKS_LIKE_XPATH.match?(rule)
      xpath(*[rule, ns, handler, binds].compact)
    else
      children.css(*[rule, ns, handler].compact) # 'children' is a smell here
    end
  end
end

#serialize

Alias for #to_s.

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 133

alias_method :serialize, :to_s

#to_html(*args)

Convert this DocumentFragment to html See NodeSet#to_html

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 67

def to_html(*args)
  if Nokogiri.jruby?
    options = args.first.is_a?(Hash) ? args.shift : {}
    options[:save_with] ||= Node::SaveOptions::DEFAULT_HTML
    args.insert(0, options)
  end
  children.to_html(*args)
end

#to_s Also known as: #serialize

Convert this DocumentFragment to a string

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 60

def to_s
  children.to_s
end

#to_xhtml(*args)

Convert this DocumentFragment to xhtml See NodeSet#to_xhtml

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 79

def to_xhtml(*args)
  if Nokogiri.jruby?
    options = args.first.is_a?(Hash) ? args.shift : {}
    options[:save_with] ||= Node::SaveOptions::DEFAULT_XHTML
    args.insert(0, options)
  end
  children.to_xhtml(*args)
end

#to_xml(*args)

Convert this DocumentFragment to xml See NodeSet#to_xml

[ GitHub ]

  
# File 'lib/nokogiri/xml/document_fragment.rb', line 91

def to_xml(*args)
  children.to_xml(*args)
end