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: | lib/nokogiri/xml/document_fragment.rb, ext/nokogiri/xml_document_fragment.c |
Overview
DocumentFragment represents a fragment of an XML document. It provides the same functionality exposed by Node and can be used to contain one or more XML subtrees.
Constant Summary
PP::Node - Included
Searchable - Included
::Nokogiri::ClassResolver - Included
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, XINCLUDE_END, XINCLUDE_START
Class Method Summary
-
.parse(input) { |options| ... } → XML::DocumentFragment)
Parse XML fragment input from a String, and return a new
DocumentFragment. - .native_new(rb_doc) Internal use only
-
.new(document) ⇒ DocumentFragment
constructor
Internal use only
Wrapper method to separate the concerns of: - the native object allocator’s parameter (it only requires
document) - the initializer’s parameters.
Node - Inherited
| .new | documented in lib/nokogiri/xml/node.rb. |
Instance Attribute Summary
-
#errors
rw
A list of
SyntaxErrorfound when parsing a document. -
#parse_options
readonly
The options used to parse the document fragment.
- #errors=(things) rw Internal use only
Node - Inherited
| #blank? |
|
| #cdata? | Returns true if this is a |
| #children | :category: Traversing Document Structure. |
| #children= | Set the content for this |
| #comment? | Returns true if this is a |
| #content | [Returns]. |
| #content= | Set the content of this node to |
| #default_namespace= | Adds a default namespace supplied as a string |
| #document | :category: Traversing Document Structure. |
| #document? | Returns true if this is a |
| #elem? | Alias for Node#element?. |
| #element? | Returns true if this is an |
| #fragment? | Returns true if this is a |
| #html? | Returns true if this is an |
| #inner_html | Get the inner_html for this node’s Node#children |
| #inner_html= | Set the content for this |
| #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 |
|
| #line= | Sets the line for this |
| #name | Alias for Node#node_name. |
| #namespace |
|
| #namespace= | Set the default namespace on this node (as would be defined with an “xmlns=” attribute in |
| #native_content= | Set the content of this node to |
| #next | Alias for Node#next_sibling. |
| #next= | Alias for Node#add_next_sibling. |
| #node_name | Returns the name for this |
| #node_name= | Set the name for this |
| #parent | |
| #parent= | |
| #previous | Alias for Node#previous_sibling. |
| #previous= | Alias for Node#add_previous_sibling. |
| #processing_instruction? | Returns true if this is a |
| #read_only? | Is this a read only node? |
| #text | Alias for Node#content. |
| #text? | Returns true if this is a |
| #to_str | Alias for Node#content. |
| #xml? | Returns true if this is an |
| #prepend_newline?, #data_ptr? | |
Instance Method Summary
-
#css(*rules, [namespace-bindings, custom-pseudo-class])
Search this fragment for
::Nokogiri::CSSrules. -
#deconstruct() → Array)
Returns the root nodes of this document fragment as an array, to use in pattern matching.
- #dup
- #fragment(data)
-
#new(document, input=nil) { |options| ... } → DocumentFragment) ⇒ DocumentFragment
constructor
Parse XML fragment input from a String, and return a new
DocumentFragmentthat is associated with the givendocument. -
#name
return the name for
DocumentFragment. -
#search(*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class])
Search this fragment for
paths. -
#serialize
Alias for #to_s.
-
#to_html(*args)
Convert this
DocumentFragmentto html See NodeSet#to_html -
#to_s
(also: #serialize)
Convert this
DocumentFragmentto a string. -
#to_xhtml(*args)
Convert this
DocumentFragmentto xhtml See NodeSet#to_xhtml -
#to_xml(*args)
Convert this
DocumentFragmentto xml See NodeSet#to_xml -
#namespace_declarations(ctx)
private
fix for issue 770.
Node - Inherited
| #<< | Add |
| #<=> | |
| #== |
|
| #[] | Fetch an attribute from this node. |
| #[]= | Update the attribute #name to |
| #accept | Accept a visitor. |
| #add_child | Appends specified Nodes to the children of |
| #add_class | Ensure HTML |
| #add_namespace | Alias for Node#add_namespace_definition. |
| #add_namespace_definition | :category: Manipulating Document Structure. |
| #add_next_sibling | Insert |
| #add_previous_sibling | Insert |
| #after | Insert |
| #ancestors | |
| #append_class | Add HTML |
| #attr | Alias for Node#[]. |
| #attribute | :category: Working With |
| #attribute_nodes | :category: Working With |
| #attribute_with_ns | :category: Working With |
| #attributes | Fetch this node’s attributes. |
| #before | Insert |
| #canonicalize, | |
| #child | :category: Traversing Document Structure. |
| #classes | Fetch CSS class names of a |
| #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 |
| #deconstruct_keys | Returns a hash describing the |
| #decorate! | Decorate this node with the decorators set up in this node’s |
| #delete | Alias for Node#remove_attribute. |
| #description | Fetch the |
| #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 |
| #element_children | [Returns]. |
| #elements | Alias for Node#element_children. |
| #encode_special_chars | Encode any special characters in |
| #external_subset | Get the external subset. |
| #first_element_child |
|
| #fragment | Create a |
| #get_attribute | Alias for Node#[]. |
| #has_attribute? | Alias for Node#key?. |
| #initialize | Create a new node with #name that belongs to |
| #internal_subset | Get the internal subset. |
| #key? | Returns true if |
| #keys | Get the attribute names for this |
| #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 |
| #last_element_child |
|
| #matches? | Returns true if this |
| #namespace_definitions | [Returns]. |
| #namespace_scopes |
|
| #namespaced_key? | Returns true if |
| #namespaces | Fetch all the namespaces on this node and its ancestors. |
| #next_element | Returns the next |
| #next_sibling | Returns the next sibling node. |
| #node_type | Get the type for this |
| #parse | Parse |
| #path | Returns the path associated with this |
| #pointer_id | [Returns]. |
| #prepend_child | Add |
| #previous_element | Returns the previous |
| #previous_sibling | Returns the previous sibling node. |
| #remove | Alias for Node#unlink. |
| #remove_attribute | Remove the attribute named #name |
| #remove_class | Remove HTML |
| #replace | Replace this |
| #serialize | Serialize Node using |
| #set_attribute | Alias for Node#[]=. |
| #swap | Swap this |
| #to_html | Serialize this |
| #to_s | Turn this node in to a string. |
| #to_xhtml | Serialize this |
| #to_xml | Serialize this |
| #traverse | Yields all children to |
| #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 |
| #wrap | Wrap this |
| #write_html_to | Write Node as |
| #write_to | Serialize this node or document to |
| #write_xhtml_to | Write Node as XHTML to |
| #write_xml_to | Write Node as |
| #add_child_node_and_reparent_attrs, #add_sibling, | |
| #compare | |
| #dump_html | Returns the |
| #get | Get the value for |
| #html_standard_serialize, | |
| #in_context | TODO: DOCUMENT ME. |
| #inspect_attributes, #keywordify, | |
| #native_write_to | Write this |
| #process_xincludes | Loads and substitutes all xinclude elements below the node. |
| #set | Set the |
| #set_namespace | Set the namespace to |
| #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. |
| #/ | Alias for Searchable#search. |
| #> | Search this node’s immediate children using |
| #at | Search this object for |
| #at_css | Search this object for |
| #at_xpath | Search this node for |
| #css | Search this object for |
| #search | Search this object for |
| #xpath | Search this node for |
| #css_internal, #css_rules_to_xpath, #xpath_impl, #xpath_internal, #xpath_query_from_css_rule, #extract_params | |
PP::Node - Included
Constructor Details
.new(document) ⇒ DocumentFragment
Wrapper method to separate the concerns of:
-
the native object allocator’s parameter (it only requires
document) -
the initializer’s parameters
# File 'lib/nokogiri/xml/document_fragment.rb', line 42
def new(document, ...) # :nodoc: instance = native_new(document) instance.send(:initialize, document, ...) instance end
#new(document, input=nil) { |options| ... } → DocumentFragment) ⇒ DocumentFragment
#new(document, input=nil, context:, options:) → DocumentFragment) ⇒ DocumentFragment
DocumentFragment
#new(document, input=nil, context:, options:) → DocumentFragment) ⇒ DocumentFragment
Parse XML fragment input from a String, and return a new DocumentFragment that is associated with the given document.
💡 It’s recommended to use either .parse or Node#parse rather than call this method directly.
- Required Parameters
-
document(XML::Document) The parent document to associate the returned fragment with.
- Optional Parameters
-
input(String) The content to be parsed.
- Optional Keyword Arguments
-
context:(Nokogiri::XML::Node) The context node for the subtree created. See below for more information. -
options:(Nokogiri::XML::ParseOptions) Configuration object that determines some behaviors during parsing. See ParseOptions for more information. The default value is ParseOptions::DEFAULT_XML.
- Yields
-
If a block is given, a Nokogiri::XML::ParseOptions object is yielded to the block which can be configured before parsing. See ParseOptions for more information.
- Returns
-
DocumentFragment
Context Node
If a context node is specified using context:, then the fragment will be created by calling Node#parse on that node, so the parser will behave as if that Node is the parent of the fragment subtree, and will resolve namespaces relative to that node.
# File 'lib/nokogiri/xml/document_fragment.rb', line 85
def initialize( document, = nil, context_ = nil, = ParseOptions::DEFAULT_XML, context: context_, options: ) # rubocop:disable Lint/MissingSuper return self unless = Nokogiri::XML::ParseOptions.new() if Integer === @parse_options = yield if block_given? children = if context # Fix for issue#490 if Nokogiri.jruby? # fix for issue #770 context.parse("<root #{namespace_declarations(context)}>#{}</root>", ).children else context.parse(, ) end else wrapper_doc = XML::Document.parse("<root>#{}</root>", nil, nil, ) self.errors = wrapper_doc.errors wrapper_doc.xpath("/root/node()") end children.each { |child| child.parent = self } end
Class Method Details
.native_new(rb_doc)
# File 'ext/nokogiri/xml_document_fragment.c', line 6
static VALUE
noko_xml_document_fragment_s_native_new(VALUE klass, VALUE rb_doc)
{
xmlDocPtr c_doc;
xmlNodePtr c_node;
VALUE rb_node;
c_doc = noko_xml_document_unwrap(rb_doc);
c_node = xmlNewDocFragment(c_doc->doc);
noko_xml_document_pin_node(c_node);
rb_node = noko_xml_node_wrap(klass, c_node);
return rb_node;
}
.parse(input) { |options| ... } → XML::DocumentFragment)
.parse(input, options:) → XML::DocumentFragment)
Parse XML fragment input from a String, and return a new DocumentFragment. This method creates a new, empty Document to contain the fragment.
- Required Parameters
-
input(String) The content to be parsed.
- Optional Keyword Arguments
-
options(Nokogiri::XML::ParseOptions) Configuration object that determines some behaviors during parsing. See ParseOptions for more information. The default value is ParseOptions::DEFAULT_XML.
- Yields
-
If a block is given, a Nokogiri::XML::ParseOptions object is yielded to the block which can be configured before parsing. See Nokogiri::XML::ParseOptions for more information.
- Returns
-
DocumentFragment
# File 'lib/nokogiri/xml/document_fragment.rb', line 35
def parse(, = ParseOptions::DEFAULT_XML, options: , &block) new(XML::Document.new, , options: , &block) end
Instance Attribute Details
#errors (rw)
A list of SyntaxError found when parsing a document
# File 'lib/nokogiri/xml/document_fragment.rb', line 207
def errors document.errors end
#errors=(things) (rw)
# File 'lib/nokogiri/xml/document_fragment.rb', line 211
def errors=(things) # :nodoc: document.errors = things end
#parse_options (readonly)
The options used to parse the document fragment. Returns the value of any options that were passed into the constructor as a parameter or set in a config block, else the default options for the specific subclass.
# File 'lib/nokogiri/xml/document_fragment.rb', line 12
attr_reader :
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
#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
# File 'lib/nokogiri/xml/document_fragment.rb', line 261
def deconstruct children.to_a end
#dup
[ GitHub ]# File 'lib/nokogiri/xml/document_fragment.rb', line 113
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 215
def fragment(data) document.fragment(data) end
#name
return the name for DocumentFragment
# File 'lib/nokogiri/xml/document_fragment.rb', line 125
def name "#document-fragment" end
#namespace_declarations(ctx) (private)
fix for issue 770
# File 'lib/nokogiri/xml/document_fragment.rb', line 268
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
# File 'lib/nokogiri/xml/document_fragment.rb', line 192
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.
# File 'lib/nokogiri/xml/document_fragment.rb', line 204
alias_method :serialize, :to_s
#to_html(*args)
Convert this DocumentFragment to html See NodeSet#to_html
# File 'lib/nokogiri/xml/document_fragment.rb', line 138
def to_html(*args) if Nokogiri.jruby? = args.first.is_a?(Hash) ? args.shift : {} [:save_with] ||= Node::SaveOptions::DEFAULT_HTML args.insert(0, ) end children.to_html(*args) end
#to_s Also known as: #serialize
Convert this DocumentFragment to a string
# File 'lib/nokogiri/xml/document_fragment.rb', line 131
def to_s children.to_s end
#to_xhtml(*args)
Convert this DocumentFragment to xhtml See NodeSet#to_xhtml
# File 'lib/nokogiri/xml/document_fragment.rb', line 150
def to_xhtml(*args) if Nokogiri.jruby? = args.first.is_a?(Hash) ? args.shift : {} [:save_with] ||= Node::SaveOptions::DEFAULT_XHTML args.insert(0, ) end children.to_xhtml(*args) end
#to_xml(*args)
Convert this DocumentFragment to xml See NodeSet#to_xml
# File 'lib/nokogiri/xml/document_fragment.rb', line 162
def to_xml(*args) children.to_xml(*args) end