nokogiri 1.10.7 → 1.16.0

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of nokogiri might be problematic. Click here for more details.

Files changed (224) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +42 -0
  3. data/LICENSE-DEPENDENCIES.md +1632 -1022
  4. data/LICENSE.md +1 -1
  5. data/README.md +188 -96
  6. data/bin/nokogiri +63 -50
  7. data/dependencies.yml +34 -66
  8. data/ext/nokogiri/depend +38 -358
  9. data/ext/nokogiri/extconf.rb +862 -421
  10. data/ext/nokogiri/gumbo.c +594 -0
  11. data/ext/nokogiri/html4_document.c +165 -0
  12. data/ext/nokogiri/html4_element_description.c +299 -0
  13. data/ext/nokogiri/html4_entity_lookup.c +37 -0
  14. data/ext/nokogiri/html4_sax_parser_context.c +108 -0
  15. data/ext/nokogiri/html4_sax_push_parser.c +95 -0
  16. data/ext/nokogiri/libxml2_backwards_compat.c +121 -0
  17. data/ext/nokogiri/nokogiri.c +251 -105
  18. data/ext/nokogiri/nokogiri.h +222 -90
  19. data/ext/nokogiri/test_global_handlers.c +40 -0
  20. data/ext/nokogiri/xml_attr.c +17 -17
  21. data/ext/nokogiri/xml_attribute_decl.c +22 -22
  22. data/ext/nokogiri/xml_cdata.c +39 -31
  23. data/ext/nokogiri/xml_comment.c +20 -27
  24. data/ext/nokogiri/xml_document.c +408 -243
  25. data/ext/nokogiri/xml_document_fragment.c +13 -17
  26. data/ext/nokogiri/xml_dtd.c +64 -58
  27. data/ext/nokogiri/xml_element_content.c +63 -55
  28. data/ext/nokogiri/xml_element_decl.c +31 -31
  29. data/ext/nokogiri/xml_encoding_handler.c +54 -21
  30. data/ext/nokogiri/xml_entity_decl.c +37 -35
  31. data/ext/nokogiri/xml_entity_reference.c +17 -19
  32. data/ext/nokogiri/xml_namespace.c +131 -61
  33. data/ext/nokogiri/xml_node.c +1343 -674
  34. data/ext/nokogiri/xml_node_set.c +246 -216
  35. data/ext/nokogiri/xml_processing_instruction.c +18 -20
  36. data/ext/nokogiri/xml_reader.c +305 -213
  37. data/ext/nokogiri/xml_relax_ng.c +87 -78
  38. data/ext/nokogiri/xml_sax_parser.c +149 -124
  39. data/ext/nokogiri/xml_sax_parser_context.c +149 -103
  40. data/ext/nokogiri/xml_sax_push_parser.c +65 -37
  41. data/ext/nokogiri/xml_schema.c +138 -82
  42. data/ext/nokogiri/xml_syntax_error.c +42 -21
  43. data/ext/nokogiri/xml_text.c +35 -26
  44. data/ext/nokogiri/xml_xpath_context.c +363 -178
  45. data/ext/nokogiri/xslt_stylesheet.c +335 -189
  46. data/gumbo-parser/CHANGES.md +63 -0
  47. data/gumbo-parser/Makefile +126 -0
  48. data/gumbo-parser/THANKS +27 -0
  49. data/gumbo-parser/src/Makefile +34 -0
  50. data/gumbo-parser/src/README.md +41 -0
  51. data/gumbo-parser/src/ascii.c +75 -0
  52. data/gumbo-parser/src/ascii.h +115 -0
  53. data/gumbo-parser/src/attribute.c +42 -0
  54. data/gumbo-parser/src/attribute.h +17 -0
  55. data/gumbo-parser/src/char_ref.c +22225 -0
  56. data/gumbo-parser/src/char_ref.h +29 -0
  57. data/gumbo-parser/src/char_ref.rl +2154 -0
  58. data/gumbo-parser/src/error.c +630 -0
  59. data/gumbo-parser/src/error.h +148 -0
  60. data/gumbo-parser/src/foreign_attrs.c +103 -0
  61. data/gumbo-parser/src/foreign_attrs.gperf +27 -0
  62. data/gumbo-parser/src/insertion_mode.h +33 -0
  63. data/gumbo-parser/src/macros.h +91 -0
  64. data/gumbo-parser/src/nokogiri_gumbo.h +944 -0
  65. data/gumbo-parser/src/parser.c +4891 -0
  66. data/gumbo-parser/src/parser.h +41 -0
  67. data/gumbo-parser/src/replacement.h +33 -0
  68. data/gumbo-parser/src/string_buffer.c +103 -0
  69. data/gumbo-parser/src/string_buffer.h +68 -0
  70. data/gumbo-parser/src/string_piece.c +48 -0
  71. data/gumbo-parser/src/svg_attrs.c +174 -0
  72. data/gumbo-parser/src/svg_attrs.gperf +77 -0
  73. data/gumbo-parser/src/svg_tags.c +137 -0
  74. data/gumbo-parser/src/svg_tags.gperf +55 -0
  75. data/gumbo-parser/src/tag.c +223 -0
  76. data/gumbo-parser/src/tag_lookup.c +382 -0
  77. data/gumbo-parser/src/tag_lookup.gperf +170 -0
  78. data/gumbo-parser/src/tag_lookup.h +13 -0
  79. data/gumbo-parser/src/token_buffer.c +79 -0
  80. data/gumbo-parser/src/token_buffer.h +71 -0
  81. data/gumbo-parser/src/token_type.h +17 -0
  82. data/gumbo-parser/src/tokenizer.c +3464 -0
  83. data/gumbo-parser/src/tokenizer.h +112 -0
  84. data/gumbo-parser/src/tokenizer_states.h +339 -0
  85. data/gumbo-parser/src/utf8.c +245 -0
  86. data/gumbo-parser/src/utf8.h +164 -0
  87. data/gumbo-parser/src/util.c +66 -0
  88. data/gumbo-parser/src/util.h +34 -0
  89. data/gumbo-parser/src/vector.c +111 -0
  90. data/gumbo-parser/src/vector.h +45 -0
  91. data/lib/nokogiri/class_resolver.rb +67 -0
  92. data/lib/nokogiri/css/node.rb +10 -8
  93. data/lib/nokogiri/css/parser.rb +397 -377
  94. data/lib/nokogiri/css/parser.y +250 -245
  95. data/lib/nokogiri/css/parser_extras.rb +54 -49
  96. data/lib/nokogiri/css/syntax_error.rb +3 -1
  97. data/lib/nokogiri/css/tokenizer.rb +5 -3
  98. data/lib/nokogiri/css/tokenizer.rex +3 -2
  99. data/lib/nokogiri/css/xpath_visitor.rb +205 -96
  100. data/lib/nokogiri/css.rb +56 -17
  101. data/lib/nokogiri/decorators/slop.rb +9 -7
  102. data/lib/nokogiri/encoding_handler.rb +57 -0
  103. data/lib/nokogiri/extension.rb +32 -0
  104. data/lib/nokogiri/gumbo.rb +15 -0
  105. data/lib/nokogiri/html.rb +38 -27
  106. data/lib/nokogiri/{html → html4}/builder.rb +4 -2
  107. data/lib/nokogiri/html4/document.rb +214 -0
  108. data/lib/nokogiri/html4/document_fragment.rb +54 -0
  109. data/lib/nokogiri/{html → html4}/element_description.rb +3 -1
  110. data/lib/nokogiri/html4/element_description_defaults.rb +2040 -0
  111. data/lib/nokogiri/html4/encoding_reader.rb +121 -0
  112. data/lib/nokogiri/{html → html4}/entity_lookup.rb +4 -2
  113. data/lib/nokogiri/{html → html4}/sax/parser.rb +17 -16
  114. data/lib/nokogiri/html4/sax/parser_context.rb +20 -0
  115. data/lib/nokogiri/{html → html4}/sax/push_parser.rb +12 -11
  116. data/lib/nokogiri/html4.rb +47 -0
  117. data/lib/nokogiri/html5/document.rb +168 -0
  118. data/lib/nokogiri/html5/document_fragment.rb +90 -0
  119. data/lib/nokogiri/html5/node.rb +103 -0
  120. data/lib/nokogiri/html5.rb +326 -0
  121. data/lib/nokogiri/jruby/dependencies.rb +3 -0
  122. data/lib/nokogiri/jruby/nokogiri_jars.rb +43 -0
  123. data/lib/nokogiri/syntax_error.rb +2 -0
  124. data/lib/nokogiri/version/constant.rb +6 -0
  125. data/lib/nokogiri/version/info.rb +224 -0
  126. data/lib/nokogiri/version.rb +3 -108
  127. data/lib/nokogiri/xml/attr.rb +55 -3
  128. data/lib/nokogiri/xml/attribute_decl.rb +6 -2
  129. data/lib/nokogiri/xml/builder.rb +75 -34
  130. data/lib/nokogiri/xml/cdata.rb +3 -1
  131. data/lib/nokogiri/xml/character_data.rb +2 -0
  132. data/lib/nokogiri/xml/document.rb +312 -127
  133. data/lib/nokogiri/xml/document_fragment.rb +93 -48
  134. data/lib/nokogiri/xml/dtd.rb +4 -2
  135. data/lib/nokogiri/xml/element_content.rb +12 -2
  136. data/lib/nokogiri/xml/element_decl.rb +6 -2
  137. data/lib/nokogiri/xml/entity_decl.rb +7 -3
  138. data/lib/nokogiri/xml/entity_reference.rb +2 -0
  139. data/lib/nokogiri/xml/namespace.rb +44 -0
  140. data/lib/nokogiri/xml/node/save_options.rb +23 -8
  141. data/lib/nokogiri/xml/node.rb +1096 -419
  142. data/lib/nokogiri/xml/node_set.rb +137 -61
  143. data/lib/nokogiri/xml/notation.rb +13 -0
  144. data/lib/nokogiri/xml/parse_options.rb +145 -52
  145. data/lib/nokogiri/xml/pp/character_data.rb +9 -6
  146. data/lib/nokogiri/xml/pp/node.rb +42 -30
  147. data/lib/nokogiri/xml/pp.rb +4 -2
  148. data/lib/nokogiri/xml/processing_instruction.rb +4 -1
  149. data/lib/nokogiri/xml/reader.rb +21 -28
  150. data/lib/nokogiri/xml/relax_ng.rb +8 -2
  151. data/lib/nokogiri/xml/sax/document.rb +45 -49
  152. data/lib/nokogiri/xml/sax/parser.rb +39 -36
  153. data/lib/nokogiri/xml/sax/parser_context.rb +8 -3
  154. data/lib/nokogiri/xml/sax/push_parser.rb +6 -5
  155. data/lib/nokogiri/xml/sax.rb +6 -4
  156. data/lib/nokogiri/xml/schema.rb +19 -9
  157. data/lib/nokogiri/xml/searchable.rb +120 -72
  158. data/lib/nokogiri/xml/syntax_error.rb +7 -5
  159. data/lib/nokogiri/xml/text.rb +2 -0
  160. data/lib/nokogiri/xml/xpath/syntax_error.rb +4 -2
  161. data/lib/nokogiri/xml/xpath.rb +15 -4
  162. data/lib/nokogiri/xml/xpath_context.rb +3 -3
  163. data/lib/nokogiri/xml.rb +39 -38
  164. data/lib/nokogiri/xslt/stylesheet.rb +3 -1
  165. data/lib/nokogiri/xslt.rb +101 -22
  166. data/lib/nokogiri.rb +59 -75
  167. data/lib/xsd/xmlparser/nokogiri.rb +29 -25
  168. data/patches/libxml2/{0004-libxml2.la-is-in-top_builddir.patch → 0003-libxml2.la-is-in-top_builddir.patch} +1 -1
  169. data/patches/libxml2/0009-allow-wildcard-namespaces.patch +77 -0
  170. data/patches/libxml2/0010-update-config.guess-and-config.sub-for-libxml2.patch +224 -0
  171. data/patches/libxml2/0011-rip-out-libxml2-s-libc_single_threaded-support.patch +30 -0
  172. data/patches/libxslt/0001-update-config.guess-and-config.sub-for-libxslt.patch +224 -0
  173. data/ports/archives/libxml2-2.12.3.tar.xz +0 -0
  174. data/ports/archives/libxslt-1.1.39.tar.xz +0 -0
  175. metadata +121 -291
  176. data/ext/nokogiri/html_document.c +0 -170
  177. data/ext/nokogiri/html_document.h +0 -10
  178. data/ext/nokogiri/html_element_description.c +0 -279
  179. data/ext/nokogiri/html_element_description.h +0 -10
  180. data/ext/nokogiri/html_entity_lookup.c +0 -32
  181. data/ext/nokogiri/html_entity_lookup.h +0 -8
  182. data/ext/nokogiri/html_sax_parser_context.c +0 -116
  183. data/ext/nokogiri/html_sax_parser_context.h +0 -11
  184. data/ext/nokogiri/html_sax_push_parser.c +0 -87
  185. data/ext/nokogiri/html_sax_push_parser.h +0 -9
  186. data/ext/nokogiri/xml_attr.h +0 -9
  187. data/ext/nokogiri/xml_attribute_decl.h +0 -9
  188. data/ext/nokogiri/xml_cdata.h +0 -9
  189. data/ext/nokogiri/xml_comment.h +0 -9
  190. data/ext/nokogiri/xml_document.h +0 -23
  191. data/ext/nokogiri/xml_document_fragment.h +0 -10
  192. data/ext/nokogiri/xml_dtd.h +0 -10
  193. data/ext/nokogiri/xml_element_content.h +0 -10
  194. data/ext/nokogiri/xml_element_decl.h +0 -9
  195. data/ext/nokogiri/xml_encoding_handler.h +0 -8
  196. data/ext/nokogiri/xml_entity_decl.h +0 -10
  197. data/ext/nokogiri/xml_entity_reference.h +0 -9
  198. data/ext/nokogiri/xml_io.c +0 -61
  199. data/ext/nokogiri/xml_io.h +0 -11
  200. data/ext/nokogiri/xml_libxml2_hacks.c +0 -112
  201. data/ext/nokogiri/xml_libxml2_hacks.h +0 -12
  202. data/ext/nokogiri/xml_namespace.h +0 -14
  203. data/ext/nokogiri/xml_node.h +0 -13
  204. data/ext/nokogiri/xml_node_set.h +0 -12
  205. data/ext/nokogiri/xml_processing_instruction.h +0 -9
  206. data/ext/nokogiri/xml_reader.h +0 -10
  207. data/ext/nokogiri/xml_relax_ng.h +0 -9
  208. data/ext/nokogiri/xml_sax_parser.h +0 -39
  209. data/ext/nokogiri/xml_sax_parser_context.h +0 -10
  210. data/ext/nokogiri/xml_sax_push_parser.h +0 -9
  211. data/ext/nokogiri/xml_schema.h +0 -9
  212. data/ext/nokogiri/xml_syntax_error.h +0 -13
  213. data/ext/nokogiri/xml_text.h +0 -9
  214. data/ext/nokogiri/xml_xpath_context.h +0 -10
  215. data/ext/nokogiri/xslt_stylesheet.h +0 -14
  216. data/lib/nokogiri/html/document.rb +0 -335
  217. data/lib/nokogiri/html/document_fragment.rb +0 -49
  218. data/lib/nokogiri/html/element_description_defaults.rb +0 -671
  219. data/lib/nokogiri/html/sax/parser_context.rb +0 -16
  220. data/patches/libxml2/0001-Revert-Do-not-URI-escape-in-server-side-includes.patch +0 -78
  221. data/ports/archives/libxml2-2.9.10.tar.gz +0 -0
  222. data/ports/archives/libxslt-1.1.34.tar.gz +0 -0
  223. /data/patches/libxml2/{0002-Remove-script-macro-support.patch → 0001-Remove-script-macro-support.patch} +0 -0
  224. /data/patches/libxml2/{0003-Update-entities-to-remove-handling-of-ssi.patch → 0002-Update-entities-to-remove-handling-of-ssi.patch} +0 -0
@@ -1,105 +1,130 @@
1
- # encoding: UTF-8
2
- require 'stringio'
3
- require 'nokogiri/xml/node/save_options'
1
+ # encoding: utf-8
2
+ # frozen_string_literal: true
3
+
4
+ require "stringio"
4
5
 
5
6
  module Nokogiri
6
7
  module XML
7
- ####
8
- # Nokogiri::XML::Node is your window to the fun filled world of dealing
9
- # with XML and HTML tags. A Nokogiri::XML::Node may be treated similarly
10
- # to a hash with regard to attributes. For example (from irb):
8
+ # Nokogiri::XML::Node is the primary API you'll use to interact with your Document.
9
+ #
10
+ # == Attributes
11
+ #
12
+ # A Nokogiri::XML::Node may be treated similarly to a hash with regard to attributes. For
13
+ # example:
14
+ #
15
+ # node = Nokogiri::XML::DocumentFragment.parse("<a href='#foo' id='link'>link</a>").at_css("a")
16
+ # node.to_html # => "<a href=\"#foo\" id=\"link\">link</a>"
17
+ # node['href'] # => "#foo"
18
+ # node.keys # => ["href", "id"]
19
+ # node.values # => ["#foo", "link"]
20
+ # node['class'] = 'green' # => "green"
21
+ # node.to_html # => "<a href=\"#foo\" id=\"link\" class=\"green\">link</a>"
22
+ #
23
+ # See the method group entitled Node@Working+With+Node+Attributes for the full set of methods.
24
+ #
25
+ # == Navigation
26
+ #
27
+ # Nokogiri::XML::Node also has methods that let you move around your tree:
11
28
  #
12
- # irb(main):004:0> node
13
- # => <a href="#foo" id="link">link</a>
14
- # irb(main):005:0> node['href']
15
- # => "#foo"
16
- # irb(main):006:0> node.keys
17
- # => ["href", "id"]
18
- # irb(main):007:0> node.values
19
- # => ["#foo", "link"]
20
- # irb(main):008:0> node['class'] = 'green'
21
- # => "green"
22
- # irb(main):009:0> node
23
- # => <a href="#foo" id="link" class="green">link</a>
24
- # irb(main):010:0>
29
+ # [#parent, #children, #next, #previous]
30
+ # Navigate up, down, or through siblings.
25
31
  #
26
- # See Nokogiri::XML::Node#[] and Nokogiri::XML#[]= for more information.
32
+ # See the method group entitled Node@Traversing+Document+Structure for the full set of methods.
27
33
  #
28
- # Nokogiri::XML::Node also has methods that let you move around your
29
- # tree. For navigating your tree, see:
34
+ # == Serialization
30
35
  #
31
- # * Nokogiri::XML::Node#parent
32
- # * Nokogiri::XML::Node#children
33
- # * Nokogiri::XML::Node#next
34
- # * Nokogiri::XML::Node#previous
36
+ # When printing or otherwise emitting a document or a node (and its subtree), there are a few
37
+ # methods you might want to use:
35
38
  #
39
+ # [#content, #text, #inner_text, #to_str]
40
+ # These methods will all **emit plaintext**,
41
+ # meaning that entities will be replaced (e.g., +&lt;+ will be replaced with +<+), meaning
42
+ # that any sanitizing will likely be un-done in the output.
36
43
  #
37
- # When printing or otherwise emitting a document or a node (and
38
- # its subtree), there are a few methods you might want to use:
44
+ # [#to_s, #to_xml, #to_html, #inner_html]
45
+ # These methods will all **emit properly-escaped markup**, meaning that it's suitable for
46
+ # consumption by browsers, parsers, etc.
39
47
  #
40
- # * content, text, inner_text, to_str: emit plaintext
48
+ # See the method group entitled Node@Serialization+and+Generating+Output for the full set of methods.
41
49
  #
42
- # These methods will all emit the plaintext version of your
43
- # document, meaning that entities will be replaced (e.g., "&lt;"
44
- # will be replaced with "<"), meaning that any sanitizing will
45
- # likely be un-done in the output.
50
+ # == Searching
46
51
  #
47
- # * to_s, to_xml, to_html, inner_html: emit well-formed markup
52
+ # You may search this node's subtree using methods like #xpath and #css.
48
53
  #
49
- # These methods will all emit properly-escaped markup, meaning
50
- # that it's suitable for consumption by browsers, parsers, etc.
54
+ # See the method group entitled Node@Searching+via+XPath+or+CSS+Queries for the full set of methods.
51
55
  #
52
- # You may search this node's subtree using Searchable#xpath and Searchable#css
53
56
  class Node
54
57
  include Nokogiri::XML::PP::Node
55
58
  include Nokogiri::XML::Searchable
59
+ include Nokogiri::ClassResolver
56
60
  include Enumerable
57
61
 
58
62
  # Element node type, see Nokogiri::XML::Node#element?
59
- ELEMENT_NODE = 1
63
+ ELEMENT_NODE = 1
60
64
  # Attribute node type
61
- ATTRIBUTE_NODE = 2
65
+ ATTRIBUTE_NODE = 2
62
66
  # Text node type, see Nokogiri::XML::Node#text?
63
- TEXT_NODE = 3
67
+ TEXT_NODE = 3
64
68
  # CDATA node type, see Nokogiri::XML::Node#cdata?
65
69
  CDATA_SECTION_NODE = 4
66
70
  # Entity reference node type
67
- ENTITY_REF_NODE = 5
71
+ ENTITY_REF_NODE = 5
68
72
  # Entity node type
69
- ENTITY_NODE = 6
73
+ ENTITY_NODE = 6
70
74
  # PI node type
71
- PI_NODE = 7
75
+ PI_NODE = 7
72
76
  # Comment node type, see Nokogiri::XML::Node#comment?
73
- COMMENT_NODE = 8
77
+ COMMENT_NODE = 8
74
78
  # Document node type, see Nokogiri::XML::Node#xml?
75
- DOCUMENT_NODE = 9
79
+ DOCUMENT_NODE = 9
76
80
  # Document type node type
77
81
  DOCUMENT_TYPE_NODE = 10
78
82
  # Document fragment node type
79
83
  DOCUMENT_FRAG_NODE = 11
80
84
  # Notation node type
81
- NOTATION_NODE = 12
85
+ NOTATION_NODE = 12
82
86
  # HTML document node type, see Nokogiri::XML::Node#html?
83
87
  HTML_DOCUMENT_NODE = 13
84
88
  # DTD node type
85
- DTD_NODE = 14
89
+ DTD_NODE = 14
86
90
  # Element declaration type
87
- ELEMENT_DECL = 15
91
+ ELEMENT_DECL = 15
88
92
  # Attribute declaration type
89
- ATTRIBUTE_DECL = 16
93
+ ATTRIBUTE_DECL = 16
90
94
  # Entity declaration type
91
- ENTITY_DECL = 17
95
+ ENTITY_DECL = 17
92
96
  # Namespace declaration type
93
- NAMESPACE_DECL = 18
97
+ NAMESPACE_DECL = 18
94
98
  # XInclude start type
95
- XINCLUDE_START = 19
99
+ XINCLUDE_START = 19
96
100
  # XInclude end type
97
- XINCLUDE_END = 20
101
+ XINCLUDE_END = 20
98
102
  # DOCB document node type
99
103
  DOCB_DOCUMENT_NODE = 21
100
104
 
101
- def initialize name, document # :nodoc:
102
- # ... Ya. This is empty on purpose.
105
+ #
106
+ # :call-seq:
107
+ # new(name, document) -> Nokogiri::XML::Node
108
+ # new(name, document) { |node| ... } -> Nokogiri::XML::Node
109
+ #
110
+ # Create a new node with +name+ that belongs to +document+.
111
+ #
112
+ # If you intend to add a node to a document tree, it's likely that you will prefer one of the
113
+ # Nokogiri::XML::Node methods like #add_child, #add_next_sibling, #replace, etc. which will
114
+ # both create an element (or subtree) and place it in the document tree.
115
+ #
116
+ # Another alternative, if you are concerned about performance, is
117
+ # Nokogiri::XML::Document#create_element which accepts additional arguments for contents or
118
+ # attributes but (like this method) avoids parsing markup.
119
+ #
120
+ # [Parameters]
121
+ # - +name+ (String)
122
+ # - +document+ (Nokogiri::XML::Document) The document to which the the returned node will belong.
123
+ # [Yields] Nokogiri::XML::Node
124
+ # [Returns] Nokogiri::XML::Node
125
+ #
126
+ def initialize(name, document)
127
+ # This is intentionally empty, and sets the method signature for subclasses.
103
128
  end
104
129
 
105
130
  ###
@@ -108,238 +133,483 @@ module Nokogiri
108
133
  document.decorate(self)
109
134
  end
110
135
 
111
- ###
112
- # Search this node's immediate children using CSS selector +selector+
113
- def > selector
114
- ns = document.root.namespaces
115
- xpath CSS.xpath_for(selector, :prefix => "./", :ns => ns).first
116
- end
117
-
118
- ###
119
- # Get the attribute value for the attribute +name+
120
- def [] name
121
- get(name.to_s)
122
- end
123
-
124
- ###
125
- # Set the attribute value for the attribute +name+ to +value+
126
- def []= name, value
127
- set name.to_s, value.to_s
128
- end
136
+ # :section: Manipulating Document Structure
129
137
 
130
138
  ###
131
139
  # Add +node_or_tags+ as a child of this Node.
132
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
133
140
  #
134
- # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
141
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
142
+ # containing markup.
143
+ #
144
+ # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
145
+ # a DocumentFragment, NodeSet, or String).
135
146
  #
136
147
  # Also see related method +<<+.
137
- def add_child node_or_tags
148
+ def add_child(node_or_tags)
138
149
  node_or_tags = coerce(node_or_tags)
139
150
  if node_or_tags.is_a?(XML::NodeSet)
140
- node_or_tags.each { |n| add_child_node_and_reparent_attrs n }
151
+ node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) }
141
152
  else
142
- add_child_node_and_reparent_attrs node_or_tags
153
+ add_child_node_and_reparent_attrs(node_or_tags)
143
154
  end
144
155
  node_or_tags
145
156
  end
146
157
 
147
158
  ###
148
159
  # Add +node_or_tags+ as the first child of this Node.
149
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
150
160
  #
151
- # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
161
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
162
+ # containing markup.
163
+ #
164
+ # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
165
+ # a DocumentFragment, NodeSet, or String).
152
166
  #
153
167
  # Also see related method +add_child+.
154
- def prepend_child node_or_tags
155
- if first = children.first
168
+ def prepend_child(node_or_tags)
169
+ if (first = children.first)
156
170
  # Mimic the error add_child would raise.
157
- raise RuntimeError, "Document already has a root node" if document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
171
+ raise "Document already has a root node" if document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
172
+
158
173
  first.__send__(:add_sibling, :previous, node_or_tags)
159
174
  else
160
175
  add_child(node_or_tags)
161
176
  end
162
177
  end
163
178
 
164
-
165
- ###
166
- # Add html around this node
179
+ # :call-seq:
180
+ # wrap(markup) -> self
181
+ # wrap(node) -> self
167
182
  #
168
- # Returns self
169
- def wrap(html)
170
- new_parent = document.parse(html).first
171
- add_next_sibling(new_parent)
183
+ # Wrap this Node with the node parsed from +markup+ or a dup of the +node+.
184
+ #
185
+ # [Parameters]
186
+ # - *markup* (String)
187
+ # Markup that is parsed and used as the wrapper. This node's parent, if it exists, is used
188
+ # as the context node for parsing; otherwise the associated document is used. If the parsed
189
+ # fragment has multiple roots, the first root node is used as the wrapper.
190
+ # - *node* (Nokogiri::XML::Node)
191
+ # An element that is `#dup`ed and used as the wrapper.
192
+ #
193
+ # [Returns] +self+, to support chaining.
194
+ #
195
+ # Also see NodeSet#wrap
196
+ #
197
+ # *Example* with a +String+ argument:
198
+ #
199
+ # doc = Nokogiri::HTML5(<<~HTML)
200
+ # <html><body>
201
+ # <a>asdf</a>
202
+ # </body></html>
203
+ # HTML
204
+ # doc.at_css("a").wrap("<div></div>")
205
+ # doc.to_html
206
+ # # => <html><head></head><body>
207
+ # # <div><a>asdf</a></div>
208
+ # # </body></html>
209
+ #
210
+ # *Example* with a +Node+ argument:
211
+ #
212
+ # doc = Nokogiri::HTML5(<<~HTML)
213
+ # <html><body>
214
+ # <a>asdf</a>
215
+ # </body></html>
216
+ # HTML
217
+ # doc.at_css("a").wrap(doc.create_element("div"))
218
+ # doc.to_html
219
+ # # <html><head></head><body>
220
+ # # <div><a>asdf</a></div>
221
+ # # </body></html>
222
+ #
223
+ def wrap(node_or_tags)
224
+ case node_or_tags
225
+ when String
226
+ context_node = parent || document
227
+ new_parent = context_node.coerce(node_or_tags).first
228
+ if new_parent.nil?
229
+ raise "Failed to parse '#{node_or_tags}' in the context of a '#{context_node.name}' element"
230
+ end
231
+ when XML::Node
232
+ new_parent = node_or_tags.dup
233
+ else
234
+ raise ArgumentError, "Requires a String or Node argument, and cannot accept a #{node_or_tags.class}"
235
+ end
236
+
237
+ if parent
238
+ add_next_sibling(new_parent)
239
+ else
240
+ new_parent.unlink
241
+ end
172
242
  new_parent.add_child(self)
243
+
173
244
  self
174
245
  end
175
246
 
176
247
  ###
177
248
  # Add +node_or_tags+ as a child of this Node.
178
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
179
249
  #
180
- # Returns self, to support chaining of calls (e.g., root << child1 << child2)
250
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
251
+ # containing markup.
252
+ #
253
+ # Returns +self+, to support chaining of calls (e.g., root << child1 << child2)
181
254
  #
182
255
  # Also see related method +add_child+.
183
- def << node_or_tags
184
- add_child node_or_tags
256
+ def <<(node_or_tags)
257
+ add_child(node_or_tags)
185
258
  self
186
259
  end
187
260
 
188
261
  ###
189
262
  # Insert +node_or_tags+ before this Node (as a sibling).
190
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
191
263
  #
192
- # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
264
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
265
+ # containing markup.
266
+ #
267
+ # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
268
+ # a DocumentFragment, NodeSet, or String).
193
269
  #
194
270
  # Also see related method +before+.
195
- def add_previous_sibling node_or_tags
196
- raise ArgumentError.new("A document may not have multiple root nodes.") if (parent && parent.document?) && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
271
+ def add_previous_sibling(node_or_tags)
272
+ raise ArgumentError,
273
+ "A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
197
274
 
198
- add_sibling :previous, node_or_tags
275
+ add_sibling(:previous, node_or_tags)
199
276
  end
200
277
 
201
278
  ###
202
279
  # Insert +node_or_tags+ after this Node (as a sibling).
203
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
204
280
  #
205
- # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
281
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
282
+ # containing markup.
283
+ #
284
+ # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
285
+ # a DocumentFragment, NodeSet, or String).
206
286
  #
207
287
  # Also see related method +after+.
208
- def add_next_sibling node_or_tags
209
- raise ArgumentError.new("A document may not have multiple root nodes.") if (parent && parent.document?) && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
288
+ def add_next_sibling(node_or_tags)
289
+ raise ArgumentError,
290
+ "A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
210
291
 
211
- add_sibling :next, node_or_tags
292
+ add_sibling(:next, node_or_tags)
212
293
  end
213
294
 
214
295
  ####
215
296
  # Insert +node_or_tags+ before this node (as a sibling).
216
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
217
297
  #
218
- # Returns self, to support chaining of calls.
298
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
299
+ # containing markup.
300
+ #
301
+ # Returns +self+, to support chaining of calls.
219
302
  #
220
303
  # Also see related method +add_previous_sibling+.
221
- def before node_or_tags
222
- add_previous_sibling node_or_tags
304
+ def before(node_or_tags)
305
+ add_previous_sibling(node_or_tags)
223
306
  self
224
307
  end
225
308
 
226
309
  ####
227
310
  # Insert +node_or_tags+ after this node (as a sibling).
228
- # +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
229
311
  #
230
- # Returns self, to support chaining of calls.
312
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a String
313
+ # containing markup.
314
+ #
315
+ # Returns +self+, to support chaining of calls.
231
316
  #
232
317
  # Also see related method +add_next_sibling+.
233
- def after node_or_tags
234
- add_next_sibling node_or_tags
318
+ def after(node_or_tags)
319
+ add_next_sibling(node_or_tags)
235
320
  self
236
321
  end
237
322
 
238
323
  ####
239
- # Set the inner html for this Node to +node_or_tags+
240
- # +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
324
+ # Set the content for this Node to +node_or_tags+.
241
325
  #
242
- # Returns self.
326
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a String
327
+ # containing markup.
328
+ #
329
+ # ⚠ Please note that despite the name, this method will *not* always parse a String argument
330
+ # as HTML. A String argument will be parsed with the +DocumentFragment+ parser related to this
331
+ # node's document.
332
+ #
333
+ # For example, if the document is an HTML4::Document then the string will be parsed as HTML4
334
+ # using HTML4::DocumentFragment; but if the document is an XML::Document then it will
335
+ # parse the string as XML using XML::DocumentFragment.
243
336
  #
244
337
  # Also see related method +children=+
245
- def inner_html= node_or_tags
338
+ def inner_html=(node_or_tags)
246
339
  self.children = node_or_tags
247
- self
248
340
  end
249
341
 
250
342
  ####
251
- # Set the inner html for this Node +node_or_tags+
252
- # +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a string containing markup.
343
+ # Set the content for this Node +node_or_tags+
253
344
  #
254
- # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
345
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a String
346
+ # containing markup.
255
347
  #
256
348
  # Also see related method +inner_html=+
257
- def children= node_or_tags
349
+ def children=(node_or_tags)
258
350
  node_or_tags = coerce(node_or_tags)
259
351
  children.unlink
260
352
  if node_or_tags.is_a?(XML::NodeSet)
261
- node_or_tags.each { |n| add_child_node_and_reparent_attrs n }
353
+ node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) }
262
354
  else
263
- add_child_node_and_reparent_attrs node_or_tags
355
+ add_child_node_and_reparent_attrs(node_or_tags)
264
356
  end
265
- node_or_tags
266
357
  end
267
358
 
268
359
  ####
269
360
  # Replace this Node with +node_or_tags+.
270
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
271
361
  #
272
- # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is a DocumentFragment, NodeSet, or string).
362
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
363
+ # containing markup.
364
+ #
365
+ # Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
366
+ # a DocumentFragment, NodeSet, or String).
273
367
  #
274
368
  # Also see related method +swap+.
275
- def replace node_or_tags
369
+ def replace(node_or_tags)
370
+ raise("Cannot replace a node with no parent") unless parent
371
+
276
372
  # We cannot replace a text node directly, otherwise libxml will return
277
373
  # an internal error at parser.c:13031, I don't know exactly why
278
374
  # libxml is trying to find a parent node that is an element or document
279
375
  # so I can't tell if this is bug in libxml or not. issue #775.
280
376
  if text?
281
- replacee = Nokogiri::XML::Node.new 'dummy', document
282
- add_previous_sibling_node replacee
377
+ replacee = Nokogiri::XML::Node.new("dummy", document)
378
+ add_previous_sibling_node(replacee)
283
379
  unlink
284
- return replacee.replace node_or_tags
380
+ return replacee.replace(node_or_tags)
285
381
  end
286
382
 
287
- node_or_tags = coerce(node_or_tags)
383
+ node_or_tags = parent.coerce(node_or_tags)
288
384
 
289
385
  if node_or_tags.is_a?(XML::NodeSet)
290
- node_or_tags.each { |n| add_previous_sibling n }
386
+ node_or_tags.each { |n| add_previous_sibling(n) }
291
387
  unlink
292
388
  else
293
- replace_node node_or_tags
389
+ replace_node(node_or_tags)
294
390
  end
295
391
  node_or_tags
296
392
  end
297
393
 
298
394
  ####
299
395
  # Swap this Node for +node_or_tags+
300
- # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a string containing markup.
396
+ #
397
+ # +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
398
+ # Containing markup.
301
399
  #
302
400
  # Returns self, to support chaining of calls.
303
401
  #
304
402
  # Also see related method +replace+.
305
- def swap node_or_tags
306
- replace node_or_tags
403
+ def swap(node_or_tags)
404
+ replace(node_or_tags)
307
405
  self
308
406
  end
309
407
 
310
- alias :next :next_sibling
311
- alias :previous :previous_sibling
312
-
313
- # :stopdoc:
314
- # HACK: This is to work around an RDoc bug
315
- alias :next= :add_next_sibling
316
- # :startdoc:
317
-
318
- alias :previous= :add_previous_sibling
319
- alias :remove :unlink
320
- alias :get_attribute :[]
321
- alias :attr :[]
322
- alias :set_attribute :[]=
323
- alias :text :content
324
- alias :inner_text :content
325
- alias :has_attribute? :key?
326
- alias :name :node_name
327
- alias :name= :node_name=
328
- alias :type :node_type
329
- alias :to_str :text
330
- alias :clone :dup
331
- alias :elements :element_children
332
-
333
408
  ####
334
- # Returns a hash containing the node's attributes. The key is
335
- # the attribute name without any namespace, the value is a Nokogiri::XML::Attr
336
- # representing the attribute.
337
- # If you need to distinguish attributes with the same name, with different namespaces
338
- # use #attribute_nodes instead.
409
+ # Set the Node's content to a Text node containing +string+. The string gets XML escaped, not
410
+ # interpreted as markup.
411
+ def content=(string)
412
+ self.native_content = encode_special_chars(string.to_s)
413
+ end
414
+
415
+ ###
416
+ # Set the parent Node for this Node
417
+ def parent=(parent_node)
418
+ parent_node.add_child(self)
419
+ end
420
+
421
+ ###
422
+ # Adds a default namespace supplied as a string +url+ href, to self.
423
+ # The consequence is as an xmlns attribute with supplied argument were
424
+ # present in parsed XML. A default namespace set with this method will
425
+ # now show up in #attributes, but when this node is serialized to XML an
426
+ # "xmlns" attribute will appear. See also #namespace and #namespace=
427
+ def default_namespace=(url)
428
+ add_namespace_definition(nil, url)
429
+ end
430
+
431
+ ###
432
+ # Set the default namespace on this node (as would be defined with an
433
+ # "xmlns=" attribute in XML source), as a Namespace object +ns+. Note that
434
+ # a Namespace added this way will NOT be serialized as an xmlns attribute
435
+ # for this node. You probably want #default_namespace= instead, or perhaps
436
+ # #add_namespace_definition with a nil prefix argument.
437
+ def namespace=(ns)
438
+ return set_namespace(ns) unless ns
439
+
440
+ unless Nokogiri::XML::Namespace === ns
441
+ raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
442
+ end
443
+ if ns.document != document
444
+ raise ArgumentError, "namespace must be declared on the same document"
445
+ end
446
+
447
+ set_namespace(ns)
448
+ end
449
+
450
+ ###
451
+ # Do xinclude substitution on the subtree below node. If given a block, a
452
+ # Nokogiri::XML::ParseOptions object initialized from +options+, will be
453
+ # passed to it, allowing more convenient modification of the parser options.
454
+ def do_xinclude(options = XML::ParseOptions::DEFAULT_XML)
455
+ options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
456
+ yield options if block_given?
457
+
458
+ # call c extension
459
+ process_xincludes(options.to_i)
460
+ end
461
+
462
+ alias_method :next, :next_sibling
463
+ alias_method :previous, :previous_sibling
464
+ alias_method :next=, :add_next_sibling
465
+ alias_method :previous=, :add_previous_sibling
466
+ alias_method :remove, :unlink
467
+ alias_method :name=, :node_name=
468
+ alias_method :add_namespace, :add_namespace_definition
469
+
470
+ # :section:
471
+
472
+ alias_method :inner_text, :content
473
+ alias_method :text, :content
474
+ alias_method :to_str, :content
475
+ alias_method :name, :node_name
476
+ alias_method :type, :node_type
477
+ alias_method :clone, :dup
478
+ alias_method :elements, :element_children
479
+
480
+ # :section: Working With Node Attributes
481
+
482
+ # :call-seq: [](name) → (String, nil)
483
+ #
484
+ # Fetch an attribute from this node.
485
+ #
486
+ # ⚠ Note that attributes with namespaces cannot be accessed with this method. To access
487
+ # namespaced attributes, use #attribute_with_ns.
488
+ #
489
+ # [Returns] (String, nil) value of the attribute +name+, or +nil+ if no matching attribute exists
490
+ #
491
+ # *Example*
492
+ #
493
+ # doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
494
+ # child = doc.at_css("child")
495
+ # child["size"] # => "large"
496
+ # child["class"] # => "big wide tall"
497
+ #
498
+ # *Example:* Namespaced attributes will not be returned.
499
+ #
500
+ # ⚠ Note namespaced attributes may be accessed with #attribute or #attribute_with_ns
501
+ #
502
+ # doc = Nokogiri::XML(<<~EOF)
503
+ # <root xmlns:width='http://example.com/widths'>
504
+ # <child width:size='broad'/>
505
+ # </root>
506
+ # EOF
507
+ # doc.at_css("child")["size"] # => nil
508
+ # doc.at_css("child").attribute("size").value # => "broad"
509
+ # doc.at_css("child").attribute_with_ns("size", "http://example.com/widths").value
510
+ # # => "broad"
511
+ #
512
+ def [](name)
513
+ get(name.to_s)
514
+ end
515
+
516
+ # :call-seq: []=(name, value) → value
517
+ #
518
+ # Update the attribute +name+ to +value+, or create the attribute if it does not exist.
519
+ #
520
+ # ⚠ Note that attributes with namespaces cannot be accessed with this method. To access
521
+ # namespaced attributes for update, use #attribute_with_ns. To add a namespaced attribute,
522
+ # see the example below.
523
+ #
524
+ # [Returns] +value+
525
+ #
526
+ # *Example*
527
+ #
528
+ # doc = Nokogiri::XML("<root><child/></root>")
529
+ # child = doc.at_css("child")
530
+ # child["size"] = "broad"
531
+ # child.to_html
532
+ # # => "<child size=\"broad\"></child>"
533
+ #
534
+ # *Example:* Add a namespaced attribute.
535
+ #
536
+ # doc = Nokogiri::XML(<<~EOF)
537
+ # <root xmlns:width='http://example.com/widths'>
538
+ # <child/>
539
+ # </root>
540
+ # EOF
541
+ # child = doc.at_css("child")
542
+ # child["size"] = "broad"
543
+ # ns = doc.root.namespace_definitions.find { |ns| ns.prefix == "width" }
544
+ # child.attribute("size").namespace = ns
545
+ # doc.to_html
546
+ # # => "<root xmlns:width=\"http://example.com/widths\">\n" +
547
+ # # " <child width:size=\"broad\"></child>\n" +
548
+ # # "</root>\n"
549
+ #
550
+ def []=(name, value)
551
+ set(name.to_s, value.to_s)
552
+ end
553
+
554
+ #
555
+ # :call-seq: attributes() → Hash<String ⇒ Nokogiri::XML::Attr>
556
+ #
557
+ # Fetch this node's attributes.
558
+ #
559
+ # ⚠ Because the keys do not include any namespace information for the attribute, in case of a
560
+ # simple name collision, not all attributes will be returned. In this case, you will need to
561
+ # use #attribute_nodes.
562
+ #
563
+ # [Returns]
564
+ # Hash containing attributes belonging to +self+. The hash keys are String attribute
565
+ # names (without the namespace), and the hash values are Nokogiri::XML::Attr.
566
+ #
567
+ # *Example* with no namespaces:
568
+ #
569
+ # doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
570
+ # doc.at_css("child").attributes
571
+ # # => {"size"=>#(Attr:0x550 { name = "size", value = "large" }),
572
+ # # "class"=>#(Attr:0x564 { name = "class", value = "big wide tall" })}
573
+ #
574
+ # *Example* with a namespace:
575
+ #
576
+ # doc = Nokogiri::XML("<root xmlns:desc='http://example.com/sizes'><child desc:size='large'/></root>")
577
+ # doc.at_css("child").attributes
578
+ # # => {"size"=>
579
+ # # #(Attr:0x550 {
580
+ # # name = "size",
581
+ # # namespace = #(Namespace:0x564 {
582
+ # # prefix = "desc",
583
+ # # href = "http://example.com/sizes"
584
+ # # }),
585
+ # # value = "large"
586
+ # # })}
587
+ #
588
+ # *Example* with an attribute name collision:
589
+ #
590
+ # ⚠ Note that only one of the attributes is returned in the Hash.
591
+ #
592
+ # doc = Nokogiri::XML(<<~EOF)
593
+ # <root xmlns:width='http://example.com/widths'
594
+ # xmlns:height='http://example.com/heights'>
595
+ # <child width:size='broad' height:size='tall'/>
596
+ # </root>
597
+ # EOF
598
+ # doc.at_css("child").attributes
599
+ # # => {"size"=>
600
+ # # #(Attr:0x550 {
601
+ # # name = "size",
602
+ # # namespace = #(Namespace:0x564 {
603
+ # # prefix = "height",
604
+ # # href = "http://example.com/heights"
605
+ # # }),
606
+ # # value = "tall"
607
+ # # })}
608
+ #
339
609
  def attributes
340
- Hash[attribute_nodes.map { |node|
341
- [node.node_name, node]
342
- }]
610
+ attribute_nodes.each_with_object({}) do |node, hash|
611
+ hash[node.node_name] = node
612
+ end
343
613
  end
344
614
 
345
615
  ###
@@ -348,6 +618,12 @@ module Nokogiri
348
618
  attribute_nodes.map(&:value)
349
619
  end
350
620
 
621
+ ###
622
+ # Does this Node's attributes include <value>
623
+ def value?(value)
624
+ values.include?(value)
625
+ end
626
+
351
627
  ###
352
628
  # Get the attribute names for this Node.
353
629
  def keys
@@ -357,97 +633,401 @@ module Nokogiri
357
633
  ###
358
634
  # Iterate over each attribute name and value pair for this Node.
359
635
  def each
360
- attribute_nodes.each { |node|
636
+ attribute_nodes.each do |node|
361
637
  yield [node.node_name, node.value]
362
- }
638
+ end
363
639
  end
364
640
 
365
641
  ###
366
- # Get the list of class names of this Node, without
367
- # deduplication or sorting.
642
+ # Remove the attribute named +name+
643
+ def remove_attribute(name)
644
+ attr = attributes[name].remove if key?(name)
645
+ clear_xpath_context if Nokogiri.jruby?
646
+ attr
647
+ end
648
+
649
+ #
650
+ # :call-seq: classes() → Array<String>
651
+ #
652
+ # Fetch CSS class names of a Node.
653
+ #
654
+ # This is a convenience function and is equivalent to:
655
+ #
656
+ # node.kwattr_values("class")
657
+ #
658
+ # See related: #kwattr_values, #add_class, #append_class, #remove_class
659
+ #
660
+ # [Returns]
661
+ # The CSS classes (Array of String) present in the Node's "class" attribute. If the
662
+ # attribute is empty or non-existent, the return value is an empty array.
663
+ #
664
+ # *Example*
665
+ #
666
+ # node # => <div class="section title header"></div>
667
+ # node.classes # => ["section", "title", "header"]
668
+ #
368
669
  def classes
369
- self['class'].to_s.scan(/\S+/)
670
+ kwattr_values("class")
370
671
  end
371
672
 
372
- ###
373
- # Add +name+ to the "class" attribute value of this Node and
374
- # return self. If the value is already in the current value, it
375
- # is not added. If no "class" attribute exists yet, one is
376
- # created with the given value.
377
673
  #
378
- # More than one class may be added at a time, separated by a
379
- # space.
380
- def add_class name
381
- names = classes
382
- self['class'] = (names + (name.scan(/\S+/) - names)).join(' ')
674
+ # :call-seq: add_class(names) self
675
+ #
676
+ # Ensure HTML CSS classes are present on +self+. Any CSS classes in +names+ that already exist
677
+ # in the "class" attribute are _not_ added. Note that any existing duplicates in the
678
+ # "class" attribute are not removed. Compare with #append_class.
679
+ #
680
+ # This is a convenience function and is equivalent to:
681
+ #
682
+ # node.kwattr_add("class", names)
683
+ #
684
+ # See related: #kwattr_add, #classes, #append_class, #remove_class
685
+ #
686
+ # [Parameters]
687
+ # - +names+ (String, Array<String>)
688
+ #
689
+ # CSS class names to be added to the Node's "class" attribute. May be a string containing
690
+ # whitespace-delimited names, or an Array of String names. Any class names already present
691
+ # will not be added. Any class names not present will be added. If no "class" attribute
692
+ # exists, one is created.
693
+ #
694
+ # [Returns] +self+ (Node) for ease of chaining method calls.
695
+ #
696
+ # *Example:* Ensure that the node has CSS class "section"
697
+ #
698
+ # node # => <div></div>
699
+ # node.add_class("section") # => <div class="section"></div>
700
+ # node.add_class("section") # => <div class="section"></div> # duplicate not added
701
+ #
702
+ # *Example:* Ensure that the node has CSS classes "section" and "header", via a String argument
703
+ #
704
+ # Note that the CSS class "section" is not added because it is already present.
705
+ # Note also that the pre-existing duplicate CSS class "section" is not removed.
706
+ #
707
+ # node # => <div class="section section"></div>
708
+ # node.add_class("section header") # => <div class="section section header"></div>
709
+ #
710
+ # *Example:* Ensure that the node has CSS classes "section" and "header", via an Array argument
711
+ #
712
+ # node # => <div></div>
713
+ # node.add_class(["section", "header"]) # => <div class="section header"></div>
714
+ #
715
+ def add_class(names)
716
+ kwattr_add("class", names)
717
+ end
718
+
719
+ #
720
+ # :call-seq: append_class(names) → self
721
+ #
722
+ # Add HTML CSS classes to +self+, regardless of duplication. Compare with #add_class.
723
+ #
724
+ # This is a convenience function and is equivalent to:
725
+ #
726
+ # node.kwattr_append("class", names)
727
+ #
728
+ # See related: #kwattr_append, #classes, #add_class, #remove_class
729
+ #
730
+ # [Parameters]
731
+ # - +names+ (String, Array<String>)
732
+ #
733
+ # CSS class names to be appended to the Node's "class" attribute. May be a string containing
734
+ # whitespace-delimited names, or an Array of String names. All class names passed in will be
735
+ # appended to the "class" attribute even if they are already present in the attribute
736
+ # value. If no "class" attribute exists, one is created.
737
+ #
738
+ # [Returns] +self+ (Node) for ease of chaining method calls.
739
+ #
740
+ # *Example:* Append "section" to the node's CSS "class" attribute
741
+ #
742
+ # node # => <div></div>
743
+ # node.append_class("section") # => <div class="section"></div>
744
+ # node.append_class("section") # => <div class="section section"></div> # duplicate added!
745
+ #
746
+ # *Example:* Append "section" and "header" to the noded's CSS "class" attribute, via a String argument
747
+ #
748
+ # Note that the CSS class "section" is appended even though it is already present
749
+ #
750
+ # node # => <div class="section section"></div>
751
+ # node.append_class("section header") # => <div class="section section section header"></div>
752
+ #
753
+ # *Example:* Append "section" and "header" to the node's CSS "class" attribute, via an Array argument
754
+ #
755
+ # node # => <div></div>
756
+ # node.append_class(["section", "header"]) # => <div class="section header"></div>
757
+ # node.append_class(["section", "header"]) # => <div class="section header section header"></div>
758
+ #
759
+ def append_class(names)
760
+ kwattr_append("class", names)
761
+ end
762
+
763
+ # :call-seq:
764
+ # remove_class(css_classes) → self
765
+ #
766
+ # Remove HTML CSS classes from this node. Any CSS class names in +css_classes+ that exist in
767
+ # this node's "class" attribute are removed, including any multiple entries.
768
+ #
769
+ # If no CSS classes remain after this operation, or if +css_classes+ is +nil+, the "class"
770
+ # attribute is deleted from the node.
771
+ #
772
+ # This is a convenience function and is equivalent to:
773
+ #
774
+ # node.kwattr_remove("class", css_classes)
775
+ #
776
+ # Also see #kwattr_remove, #classes, #add_class, #append_class
777
+ #
778
+ # [Parameters]
779
+ # - +css_classes+ (String, Array<String>)
780
+ #
781
+ # CSS class names to be removed from the Node's
782
+ # "class" attribute. May be a string containing whitespace-delimited names, or an Array of
783
+ # String names. Any class names already present will be removed. If no CSS classes remain,
784
+ # the "class" attribute is deleted.
785
+ #
786
+ # [Returns] +self+ (Nokogiri::XML::Node) for ease of chaining method calls.
787
+ #
788
+ # *Example*: Deleting a CSS class
789
+ #
790
+ # Note that all instances of the class "section" are removed from the "class" attribute.
791
+ #
792
+ # node # => <div class="section header section"></div>
793
+ # node.remove_class("section") # => <div class="header"></div>
794
+ #
795
+ # *Example*: Deleting the only remaining CSS class
796
+ #
797
+ # Note that the attribute is removed once there are no remaining classes.
798
+ #
799
+ # node # => <div class="section"></div>
800
+ # node.remove_class("section") # => <div></div>
801
+ #
802
+ # *Example*: Deleting multiple CSS classes
803
+ #
804
+ # Note that the "class" attribute is deleted once it's empty.
805
+ #
806
+ # node # => <div class="section header float"></div>
807
+ # node.remove_class(["section", "float"]) # => <div class="header"></div>
808
+ #
809
+ def remove_class(names = nil)
810
+ kwattr_remove("class", names)
811
+ end
812
+
813
+ # :call-seq:
814
+ # kwattr_values(attribute_name) → Array<String>
815
+ #
816
+ # Fetch values from a keyword attribute of a Node.
817
+ #
818
+ # A "keyword attribute" is a node attribute that contains a set of space-delimited
819
+ # values. Perhaps the most familiar example of this is the HTML "class" attribute used to
820
+ # contain CSS classes. But other keyword attributes exist, for instance
821
+ # {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
822
+ #
823
+ # See also #classes, #kwattr_add, #kwattr_append, #kwattr_remove
824
+ #
825
+ # [Parameters]
826
+ # - +attribute_name+ (String) The name of the keyword attribute to be inspected.
827
+ #
828
+ # [Returns]
829
+ # (Array<String>) The values present in the Node's +attribute_name+ attribute. If the
830
+ # attribute is empty or non-existent, the return value is an empty array.
831
+ #
832
+ # *Example:*
833
+ #
834
+ # node # => <a rel="nofollow noopener external">link</a>
835
+ # node.kwattr_values("rel") # => ["nofollow", "noopener", "external"]
836
+ #
837
+ # Since v1.11.0
838
+ def kwattr_values(attribute_name)
839
+ keywordify(get_attribute(attribute_name) || [])
840
+ end
841
+
842
+ # :call-seq:
843
+ # kwattr_add(attribute_name, keywords) → self
844
+ #
845
+ # Ensure that values are present in a keyword attribute.
846
+ #
847
+ # Any values in +keywords+ that already exist in the Node's attribute values are _not_
848
+ # added. Note that any existing duplicates in the attribute values are not removed. Compare
849
+ # with #kwattr_append.
850
+ #
851
+ # A "keyword attribute" is a node attribute that contains a set of space-delimited
852
+ # values. Perhaps the most familiar example of this is the HTML "class" attribute used to
853
+ # contain CSS classes. But other keyword attributes exist, for instance
854
+ # {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
855
+ #
856
+ # See also #add_class, #kwattr_values, #kwattr_append, #kwattr_remove
857
+ #
858
+ # [Parameters]
859
+ # - +attribute_name+ (String) The name of the keyword attribute to be modified.
860
+ # - +keywords+ (String, Array<String>)
861
+ # Keywords to be added to the attribute named +attribute_name+. May be a string containing
862
+ # whitespace-delimited values, or an Array of String values. Any values already present will
863
+ # not be added. Any values not present will be added. If the named attribute does not exist,
864
+ # it is created.
865
+ #
866
+ # [Returns] +self+ (Nokogiri::XML::Node) for ease of chaining method calls.
867
+ #
868
+ # *Example:* Ensure that a +Node+ has "nofollow" in its +rel+ attribute.
869
+ #
870
+ # Note that duplicates are not added.
871
+ #
872
+ # node # => <a></a>
873
+ # node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a>
874
+ # node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a>
875
+ #
876
+ # *Example:* Ensure that a +Node+ has "nofollow" and "noreferrer" in its +rel+ attribute, via a
877
+ # String argument.
878
+ #
879
+ # Note that "nofollow" is not added because it is already present. Note also that the
880
+ # pre-existing duplicate "nofollow" is not removed.
881
+ #
882
+ # node # => <a rel="nofollow nofollow"></a>
883
+ # node.kwattr_add("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a>
884
+ #
885
+ # *Example:* Ensure that a +Node+ has "nofollow" and "noreferrer" in its +rel+ attribute, via
886
+ # an Array argument.
887
+ #
888
+ # node # => <a></a>
889
+ # node.kwattr_add("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a>
890
+ #
891
+ # Since v1.11.0
892
+ def kwattr_add(attribute_name, keywords)
893
+ keywords = keywordify(keywords)
894
+ current_kws = kwattr_values(attribute_name)
895
+ new_kws = (current_kws + (keywords - current_kws)).join(" ")
896
+ set_attribute(attribute_name, new_kws)
383
897
  self
384
898
  end
385
899
 
386
- ###
387
- # Append +name+ to the "class" attribute value of this Node and
388
- # return self. The value is simply appended without checking if
389
- # it is already in the current value. If no "class" attribute
390
- # exists yet, one is created with the given value.
900
+ # :call-seq:
901
+ # kwattr_append(attribute_name, keywords) self
902
+ #
903
+ # Add keywords to a Node's keyword attribute, regardless of duplication. Compare with
904
+ # #kwattr_add.
905
+ #
906
+ # A "keyword attribute" is a node attribute that contains a set of space-delimited
907
+ # values. Perhaps the most familiar example of this is the HTML "class" attribute used to
908
+ # contain CSS classes. But other keyword attributes exist, for instance
909
+ # {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
910
+ #
911
+ # See also #append_class, #kwattr_values, #kwattr_add, #kwattr_remove
391
912
  #
392
- # More than one class may be appended at a time, separated by a
393
- # space.
394
- def append_class name
395
- self['class'] = (classes + name.scan(/\S+/)).join(' ')
913
+ # [Parameters]
914
+ # - +attribute_name+ (String) The name of the keyword attribute to be modified.
915
+ # - +keywords+ (String, Array<String>)
916
+ # Keywords to be added to the attribute named +attribute_name+. May be a string containing
917
+ # whitespace-delimited values, or an Array of String values. All values passed in will be
918
+ # appended to the named attribute even if they are already present in the attribute. If the
919
+ # named attribute does not exist, it is created.
920
+ #
921
+ # [Returns] +self+ (Node) for ease of chaining method calls.
922
+ #
923
+ # *Example:* Append "nofollow" to the +rel+ attribute.
924
+ #
925
+ # Note that duplicates are added.
926
+ #
927
+ # node # => <a></a>
928
+ # node.kwattr_append("rel", "nofollow") # => <a rel="nofollow"></a>
929
+ # node.kwattr_append("rel", "nofollow") # => <a rel="nofollow nofollow"></a>
930
+ #
931
+ # *Example:* Append "nofollow" and "noreferrer" to the +rel+ attribute, via a String argument.
932
+ #
933
+ # Note that "nofollow" is appended even though it is already present.
934
+ #
935
+ # node # => <a rel="nofollow"></a>
936
+ # node.kwattr_append("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a>
937
+ #
938
+ #
939
+ # *Example:* Append "nofollow" and "noreferrer" to the +rel+ attribute, via an Array argument.
940
+ #
941
+ # node # => <a></a>
942
+ # node.kwattr_append("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a>
943
+ #
944
+ # Since v1.11.0
945
+ def kwattr_append(attribute_name, keywords)
946
+ keywords = keywordify(keywords)
947
+ current_kws = kwattr_values(attribute_name)
948
+ new_kws = (current_kws + keywords).join(" ")
949
+ set_attribute(attribute_name, new_kws)
396
950
  self
397
951
  end
398
952
 
399
- ###
400
- # Remove +name+ from the "class" attribute value of this Node
401
- # and return self. If there are many occurrences of the name,
402
- # they are all removed.
953
+ # :call-seq:
954
+ # kwattr_remove(attribute_name, keywords) self
403
955
  #
404
- # More than one class may be removed at a time, separated by a
405
- # space.
956
+ # Remove keywords from a keyword attribute. Any matching keywords that exist in the named
957
+ # attribute are removed, including any multiple entries.
406
958
  #
407
- # If no class name is left after removal, or when +name+ is nil,
408
- # the "class" attribute is removed from this Node.
409
- def remove_class name = nil
410
- if name
411
- names = classes - name.scan(/\S+/)
412
- if names.empty?
413
- delete 'class'
414
- else
415
- self['class'] = names.join(' ')
416
- end
959
+ # If no keywords remain after this operation, or if +keywords+ is +nil+, the attribute is
960
+ # deleted from the node.
961
+ #
962
+ # A "keyword attribute" is a node attribute that contains a set of space-delimited
963
+ # values. Perhaps the most familiar example of this is the HTML "class" attribute used to
964
+ # contain CSS classes. But other keyword attributes exist, for instance
965
+ # {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
966
+ #
967
+ # See also #remove_class, #kwattr_values, #kwattr_add, #kwattr_append
968
+ #
969
+ # [Parameters]
970
+ # - +attribute_name+ (String) The name of the keyword attribute to be modified.
971
+ # - +keywords+ (String, Array<String>)
972
+ # Keywords to be removed from the attribute named +attribute_name+. May be a string
973
+ # containing whitespace-delimited values, or an Array of String values. Any keywords present
974
+ # in the named attribute will be removed. If no keywords remain, or if +keywords+ is nil,
975
+ # the attribute is deleted.
976
+ #
977
+ # [Returns] +self+ (Node) for ease of chaining method calls.
978
+ #
979
+ # *Example:*
980
+ #
981
+ # Note that the +rel+ attribute is deleted when empty.
982
+ #
983
+ # node # => <a rel="nofollow noreferrer">link</a>
984
+ # node.kwattr_remove("rel", "nofollow") # => <a rel="noreferrer">link</a>
985
+ # node.kwattr_remove("rel", "noreferrer") # => <a>link</a>
986
+ #
987
+ # Since v1.11.0
988
+ def kwattr_remove(attribute_name, keywords)
989
+ if keywords.nil?
990
+ remove_attribute(attribute_name)
991
+ return self
992
+ end
993
+
994
+ keywords = keywordify(keywords)
995
+ current_kws = kwattr_values(attribute_name)
996
+ new_kws = current_kws - keywords
997
+ if new_kws.empty?
998
+ remove_attribute(attribute_name)
417
999
  else
418
- delete "class"
1000
+ set_attribute(attribute_name, new_kws.join(" "))
419
1001
  end
420
1002
  self
421
1003
  end
422
1004
 
423
- ###
424
- # Remove the attribute named +name+
425
- def remove_attribute name
426
- attr = attributes[name].remove if key? name
427
- clear_xpath_context if Nokogiri.jruby?
428
- attr
429
- end
430
- alias :delete :remove_attribute
1005
+ alias_method :delete, :remove_attribute
1006
+ alias_method :get_attribute, :[]
1007
+ alias_method :attr, :[]
1008
+ alias_method :set_attribute, :[]=
1009
+ alias_method :has_attribute?, :key?
1010
+
1011
+ # :section:
431
1012
 
432
1013
  ###
433
1014
  # Returns true if this Node matches +selector+
434
- def matches? selector
1015
+ def matches?(selector)
435
1016
  ancestors.last.search(selector).include?(self)
436
1017
  end
437
1018
 
438
1019
  ###
439
1020
  # Create a DocumentFragment containing +tags+ that is relative to _this_
440
1021
  # context node.
441
- def fragment tags
442
- type = document.html? ? Nokogiri::HTML : Nokogiri::XML
443
- type::DocumentFragment.new(document, tags, self)
1022
+ def fragment(tags)
1023
+ document.related_class("DocumentFragment").new(document, tags, self)
444
1024
  end
445
1025
 
446
1026
  ###
447
1027
  # Parse +string_or_io+ as a document fragment within the context of
448
1028
  # *this* node. Returns a XML::NodeSet containing the nodes parsed from
449
1029
  # +string_or_io+.
450
- def parse string_or_io, options = nil
1030
+ def parse(string_or_io, options = nil)
451
1031
  ##
452
1032
  # When the current node is unparented and not an element node, use the
453
1033
  # document as the parsing context instead. Otherwise, the in-context
@@ -458,61 +1038,93 @@ module Nokogiri
458
1038
  end
459
1039
 
460
1040
  options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML)
461
- if Integer === options
462
- options = Nokogiri::XML::ParseOptions.new(options)
463
- end
464
- # Give the options to the user
1041
+ options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
465
1042
  yield options if block_given?
466
1043
 
467
- contents = string_or_io.respond_to?(:read) ?
468
- string_or_io.read :
1044
+ contents = if string_or_io.respond_to?(:read)
1045
+ string_or_io.read
1046
+ else
469
1047
  string_or_io
1048
+ end
470
1049
 
471
1050
  return Nokogiri::XML::NodeSet.new(document) if contents.empty?
472
1051
 
473
- ##
474
- # This is a horrible hack, but I don't care. See #313 for background.
475
1052
  error_count = document.errors.length
476
1053
  node_set = in_context(contents, options.to_i)
477
- if node_set.empty? and document.errors.length > error_count and options.recover?
478
- fragment = Nokogiri::HTML::DocumentFragment.parse contents
479
- node_set = fragment.children
1054
+ if document.errors.length > error_count
1055
+ raise document.errors[error_count] unless options.recover?
1056
+
1057
+ if node_set.empty?
1058
+ # libxml2 < 2.13 does not obey the +recover+ option after encountering errors during
1059
+ # +in_context+ parsing, and so this horrible hack is here to try to emulate recovery
1060
+ # behavior.
1061
+ #
1062
+ # (Note that HTML4 fragment parsing seems to have been fixed in abd74186, and XML
1063
+ # fragment parsing is fixed in 1c106edf. Both are in 2.13.)
1064
+ #
1065
+ # Unfortunately, this means we're no longer parsing "in context" and so namespaces that
1066
+ # would have been inherited from the context node won't be handled correctly. This hack
1067
+ # was written in 2010, and I regret it, because it's silently degrading functionality in
1068
+ # a way that's not easily prevented (or even detected).
1069
+ #
1070
+ # I think preferable behavior would be to either:
1071
+ #
1072
+ # a. add an error noting that we "fell back" and pointing the user to turning off the
1073
+ # +recover+ option
1074
+ # b. don't recover, but raise a sensible exception
1075
+ #
1076
+ # For context and background:
1077
+ # - https://github.com/sparklemotion/nokogiri/issues/313
1078
+ # - https://github.com/sparklemotion/nokogiri/issues/2092
1079
+ fragment = document.related_class("DocumentFragment").parse(contents)
1080
+ node_set = fragment.children
1081
+ end
480
1082
  end
481
1083
  node_set
482
1084
  end
483
1085
 
484
- ####
485
- # Set the Node's content to a Text node containing +string+. The string gets XML escaped, not interpreted as markup.
486
- def content= string
487
- self.native_content = encode_special_chars(string.to_s)
488
- end
489
-
490
- ###
491
- # Set the parent Node for this Node
492
- def parent= parent_node
493
- parent_node.add_child(self)
494
- parent_node
495
- end
496
-
497
- ###
498
- # Returns a Hash of +{prefix => value}+ for all namespaces on this
499
- # node and its ancestors.
1086
+ # :call-seq:
1087
+ # namespaces() Hash<String(Namespace#prefix) String(Namespace#href)>
1088
+ #
1089
+ # Fetch all the namespaces on this node and its ancestors.
1090
+ #
1091
+ # Note that the keys in this hash XML attributes that would be used to define this namespace,
1092
+ # such as "xmlns:prefix", not just the prefix.
1093
+ #
1094
+ # The default namespace for this node will be included with key "xmlns".
1095
+ #
1096
+ # See also #namespace_scopes
1097
+ #
1098
+ # [Returns]
1099
+ # Hash containing all the namespaces on this node and its ancestors. The hash keys are the
1100
+ # namespace prefix, and the hash value for each key is the namespace URI.
1101
+ #
1102
+ # *Example:*
500
1103
  #
501
- # This method returns the same namespaces as #namespace_scopes.
1104
+ # doc = Nokogiri::XML(<<~EOF)
1105
+ # <root xmlns="http://example.com/root" xmlns:in_scope="http://example.com/in_scope">
1106
+ # <first/>
1107
+ # <second xmlns="http://example.com/child"/>
1108
+ # <third xmlns:foo="http://example.com/foo"/>
1109
+ # </root>
1110
+ # EOF
1111
+ # doc.at_xpath("//root:first", "root" => "http://example.com/root").namespaces
1112
+ # # => {"xmlns"=>"http://example.com/root",
1113
+ # # "xmlns:in_scope"=>"http://example.com/in_scope"}
1114
+ # doc.at_xpath("//child:second", "child" => "http://example.com/child").namespaces
1115
+ # # => {"xmlns"=>"http://example.com/child",
1116
+ # # "xmlns:in_scope"=>"http://example.com/in_scope"}
1117
+ # doc.at_xpath("//root:third", "root" => "http://example.com/root").namespaces
1118
+ # # => {"xmlns:foo"=>"http://example.com/foo",
1119
+ # # "xmlns"=>"http://example.com/root",
1120
+ # # "xmlns:in_scope"=>"http://example.com/in_scope"}
502
1121
  #
503
- # Returns namespaces in scope for self -- those defined on self
504
- # element directly or any ancestor node -- as a Hash of
505
- # attribute-name/value pairs. Note that the keys in this hash
506
- # XML attributes that would be used to define this namespace,
507
- # such as "xmlns:prefix", not just the prefix. Default namespace
508
- # set on self will be included with key "xmlns". However,
509
- # default namespaces set on ancestor will NOT be, even if self
510
- # has no explicit default namespace.
511
1122
  def namespaces
512
- Hash[namespace_scopes.map { |nd|
513
- key = ['xmlns', nd.prefix].compact.join(':')
514
- [key, nd.href]
515
- }]
1123
+ namespace_scopes.each_with_object({}) do |ns, hash|
1124
+ prefix = ns.prefix
1125
+ key = prefix ? "xmlns:#{prefix}" : "xmlns"
1126
+ hash[key] = ns.href
1127
+ end
516
1128
  end
517
1129
 
518
1130
  # Returns true if this is a Comment
@@ -530,14 +1142,14 @@ module Nokogiri
530
1142
  type == DOCUMENT_NODE
531
1143
  end
532
1144
 
533
- # Returns true if this is an HTML::Document node
1145
+ # Returns true if this is an HTML4::Document or HTML5::Document node
534
1146
  def html?
535
1147
  type == HTML_DOCUMENT_NODE
536
1148
  end
537
1149
 
538
1150
  # Returns true if this is a Document
539
1151
  def document?
540
- is_a? XML::Document
1152
+ is_a?(XML::Document)
541
1153
  end
542
1154
 
543
1155
  # Returns true if this is a ProcessingInstruction node
@@ -556,11 +1168,12 @@ module Nokogiri
556
1168
  end
557
1169
 
558
1170
  ###
559
- # Fetch the Nokogiri::HTML::ElementDescription for this node. Returns
1171
+ # Fetch the Nokogiri::HTML4::ElementDescription for this node. Returns
560
1172
  # nil on XML documents and on unknown tags.
561
1173
  def description
562
- return nil if document.xml?
563
- Nokogiri::HTML::ElementDescription[name]
1174
+ return if document.xml?
1175
+
1176
+ Nokogiri::HTML4::ElementDescription[name]
564
1177
  end
565
1178
 
566
1179
  ###
@@ -574,7 +1187,8 @@ module Nokogiri
574
1187
  def element?
575
1188
  type == ELEMENT_NODE
576
1189
  end
577
- alias :elem? :element?
1190
+
1191
+ alias_method :elem?, :element?
578
1192
 
579
1193
  ###
580
1194
  # Turn this node in to a string. If the document is HTML, this method
@@ -584,28 +1198,29 @@ module Nokogiri
584
1198
  end
585
1199
 
586
1200
  # Get the inner_html for this node's Node#children
587
- def inner_html *args
1201
+ def inner_html(*args)
588
1202
  children.map { |x| x.to_html(*args) }.join
589
1203
  end
590
1204
 
591
1205
  # Get the path to this node as a CSS expression
592
1206
  def css_path
593
- path.split(/\//).map { |part|
594
- part.length == 0 ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
595
- }.compact.join(' > ')
1207
+ path.split(%r{/}).filter_map do |part|
1208
+ part.empty? ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)')
1209
+ end.join(" > ")
596
1210
  end
597
1211
 
598
1212
  ###
599
1213
  # Get a list of ancestor Node for this Node. If +selector+ is given,
600
1214
  # the ancestors must match +selector+
601
- def ancestors selector = nil
1215
+ def ancestors(selector = nil)
602
1216
  return NodeSet.new(document) unless respond_to?(:parent)
603
1217
  return NodeSet.new(document) unless parent
604
1218
 
605
1219
  parents = [parent]
606
1220
 
607
1221
  while parents.last.respond_to?(:parent)
608
- break unless ctx_parent = parents.last.parent
1222
+ break unless (ctx_parent = parents.last.parent)
1223
+
609
1224
  parents << ctx_parent
610
1225
  end
611
1226
 
@@ -614,89 +1229,77 @@ module Nokogiri
614
1229
  root = parents.last
615
1230
  search_results = root.search(selector)
616
1231
 
617
- NodeSet.new(document, parents.find_all { |parent|
1232
+ NodeSet.new(document, parents.find_all do |parent|
618
1233
  search_results.include?(parent)
619
- })
620
- end
621
-
622
- ###
623
- # Adds a default namespace supplied as a string +url+ href, to self.
624
- # The consequence is as an xmlns attribute with supplied argument were
625
- # present in parsed XML. A default namespace set with this method will
626
- # now show up in #attributes, but when this node is serialized to XML an
627
- # "xmlns" attribute will appear. See also #namespace and #namespace=
628
- def default_namespace= url
629
- add_namespace_definition(nil, url)
630
- end
631
- alias :add_namespace :add_namespace_definition
632
-
633
- ###
634
- # Set the default namespace on this node (as would be defined with an
635
- # "xmlns=" attribute in XML source), as a Namespace object +ns+. Note that
636
- # a Namespace added this way will NOT be serialized as an xmlns attribute
637
- # for this node. You probably want #default_namespace= instead, or perhaps
638
- # #add_namespace_definition with a nil prefix argument.
639
- def namespace= ns
640
- return set_namespace(ns) unless ns
641
-
642
- unless Nokogiri::XML::Namespace === ns
643
- raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
644
- end
645
- if ns.document != document
646
- raise ArgumentError, 'namespace must be declared on the same document'
647
- end
648
-
649
- set_namespace ns
1234
+ end)
650
1235
  end
651
1236
 
652
1237
  ####
653
1238
  # Yields self and all children to +block+ recursively.
654
- def traverse &block
655
- children.each{|j| j.traverse(&block) }
656
- block.call(self)
1239
+ def traverse(&block)
1240
+ children.each { |j| j.traverse(&block) }
1241
+ yield(self)
657
1242
  end
658
1243
 
659
1244
  ###
660
1245
  # Accept a visitor. This method calls "visit" on +visitor+ with self.
661
- def accept visitor
1246
+ def accept(visitor)
662
1247
  visitor.visit(self)
663
1248
  end
664
1249
 
665
1250
  ###
666
1251
  # Test to see if this Node is equal to +other+
667
- def == other
1252
+ def ==(other)
668
1253
  return false unless other
669
1254
  return false unless other.respond_to?(:pointer_id)
1255
+
670
1256
  pointer_id == other.pointer_id
671
1257
  end
672
1258
 
673
1259
  ###
674
- # Serialize Node using +options+. Save options can also be set using a
675
- # block. See SaveOptions.
1260
+ # Compare two Node objects with respect to their Document. Nodes from
1261
+ # different documents cannot be compared.
1262
+ def <=>(other)
1263
+ return unless other.is_a?(Nokogiri::XML::Node)
1264
+ return unless document == other.document
1265
+
1266
+ compare(other)
1267
+ end
1268
+
1269
+ # :section: Serialization and Generating Output
1270
+
1271
+ ###
1272
+ # Serialize Node using +options+. Save options can also be set using a block.
1273
+ #
1274
+ # See also Nokogiri::XML::Node::SaveOptions and Node@Serialization+and+Generating+Output.
676
1275
  #
677
1276
  # These two statements are equivalent:
678
1277
  #
679
- # node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML)
1278
+ # node.serialize(encoding: 'UTF-8', save_with: FORMAT | AS_XML)
680
1279
  #
681
1280
  # or
682
1281
  #
683
- # node.serialize(:encoding => 'UTF-8') do |config|
1282
+ # node.serialize(encoding: 'UTF-8') do |config|
684
1283
  # config.format.as_xml
685
1284
  # end
686
1285
  #
687
- def serialize *args, &block
688
- options = args.first.is_a?(Hash) ? args.shift : {
689
- :encoding => args[0],
690
- :save_with => args[1]
691
- }
1286
+ def serialize(*args, &block)
1287
+ # TODO: deprecate non-hash options, see 46c68ed 2009-06-20 for context
1288
+ options = if args.first.is_a?(Hash)
1289
+ args.shift
1290
+ else
1291
+ {
1292
+ encoding: args[0],
1293
+ save_with: args[1],
1294
+ }
1295
+ end
1296
+
1297
+ options[:encoding] ||= document.encoding
1298
+ encoding = Encoding.find(options[:encoding] || "UTF-8")
692
1299
 
693
- encoding = options[:encoding] || document.encoding
694
- options[:encoding] = encoding
1300
+ io = StringIO.new(String.new(encoding: encoding))
695
1301
 
696
- outstring = String.new
697
- outstring.force_encoding(Encoding.find(encoding || 'utf-8'))
698
- io = StringIO.new(outstring)
699
- write_to io, options, &block
1302
+ write_to(io, options, &block)
700
1303
  io.string
701
1304
  end
702
1305
 
@@ -707,17 +1310,17 @@ module Nokogiri
707
1310
  #
708
1311
  # See Node#write_to for a list of +options+. For formatted output,
709
1312
  # use Node#to_xhtml instead.
710
- def to_html options = {}
711
- to_format SaveOptions::DEFAULT_HTML, options
1313
+ def to_html(options = {})
1314
+ to_format(SaveOptions::DEFAULT_HTML, options)
712
1315
  end
713
1316
 
714
1317
  ###
715
1318
  # Serialize this Node to XML using +options+
716
1319
  #
717
- # doc.to_xml(:indent => 5, :encoding => 'UTF-8')
1320
+ # doc.to_xml(indent: 5, encoding: 'UTF-8')
718
1321
  #
719
1322
  # See Node#write_to for a list of +options+
720
- def to_xml options = {}
1323
+ def to_xml(options = {})
721
1324
  options[:save_with] ||= SaveOptions::DEFAULT_XML
722
1325
  serialize(options)
723
1326
  end
@@ -725,62 +1328,76 @@ module Nokogiri
725
1328
  ###
726
1329
  # Serialize this Node to XHTML using +options+
727
1330
  #
728
- # doc.to_xhtml(:indent => 5, :encoding => 'UTF-8')
1331
+ # doc.to_xhtml(indent: 5, encoding: 'UTF-8')
729
1332
  #
730
1333
  # See Node#write_to for a list of +options+
731
- def to_xhtml options = {}
732
- to_format SaveOptions::DEFAULT_XHTML, options
1334
+ def to_xhtml(options = {})
1335
+ to_format(SaveOptions::DEFAULT_XHTML, options)
733
1336
  end
734
1337
 
735
1338
  ###
736
- # Write Node to +io+ with +options+. +options+ modify the output of
737
- # this method. Valid options are:
1339
+ # :call-seq:
1340
+ # write_to(io, *options)
1341
+ #
1342
+ # Serialize this node or document to +io+.
1343
+ #
1344
+ # [Parameters]
1345
+ # - +io+ (IO) An IO-like object to which the serialized content will be written.
1346
+ # - +options+ (Hash) See below
738
1347
  #
739
- # * +:encoding+ for changing the encoding
740
- # * +:indent_text+ the indentation text, defaults to one space
741
- # * +:indent+ the number of +:indent_text+ to use, defaults to 2
742
- # * +:save_with+ a combination of SaveOptions constants.
1348
+ # [Options]
1349
+ # * +:encoding+ (String or Encoding) specify the encoding of the output (defaults to document encoding)
1350
+ # * +:indent_text+ (String) the indentation text (defaults to <code>" "</code>)
1351
+ # * +:indent+ (Integer) the number of +:indent_text+ to use (defaults to +2+)
1352
+ # * +:save_with+ (Integer) a combination of SaveOptions constants
743
1353
  #
744
1354
  # To save with UTF-8 indented twice:
745
1355
  #
746
- # node.write_to(io, :encoding => 'UTF-8', :indent => 2)
1356
+ # node.write_to(io, encoding: 'UTF-8', indent: 2)
747
1357
  #
748
1358
  # To save indented with two dashes:
749
1359
  #
750
- # node.write_to(io, :indent_text => '-', :indent => 2)
1360
+ # node.write_to(io, indent_text: '-', indent: 2)
751
1361
  #
752
- def write_to io, *options
753
- options = options.first.is_a?(Hash) ? options.shift : {}
754
- encoding = options[:encoding] || options[0]
1362
+ def write_to(io, *options)
1363
+ options = options.first.is_a?(Hash) ? options.shift : {}
1364
+ encoding = options[:encoding] || options[0] || document.encoding
755
1365
  if Nokogiri.jruby?
756
- save_options = options[:save_with] || options[1]
757
- indent_times = options[:indent] || 0
1366
+ save_options = options[:save_with] || options[1]
1367
+ indent_times = options[:indent] || 0
758
1368
  else
759
- save_options = options[:save_with] || options[1] || SaveOptions::FORMAT
760
- indent_times = options[:indent] || 2
1369
+ save_options = options[:save_with] || options[1] || SaveOptions::FORMAT
1370
+ indent_times = options[:indent] || 2
761
1371
  end
762
- indent_text = options[:indent_text] || ' '
1372
+ indent_text = options[:indent_text] || " "
1373
+
1374
+ # Any string times 0 returns an empty string. Therefore, use the same
1375
+ # string instead of generating a new empty string for every node with
1376
+ # zero indentation.
1377
+ indentation = indent_times.zero? ? "" : (indent_text * indent_times)
763
1378
 
764
1379
  config = SaveOptions.new(save_options.to_i)
765
1380
  yield config if block_given?
766
1381
 
767
- native_write_to(io, encoding, indent_text * indent_times, config.options)
1382
+ encoding = encoding.is_a?(Encoding) ? encoding.name : encoding
1383
+
1384
+ native_write_to(io, encoding, indentation, config.options)
768
1385
  end
769
1386
 
770
1387
  ###
771
1388
  # Write Node as HTML to +io+ with +options+
772
1389
  #
773
1390
  # See Node#write_to for a list of +options+
774
- def write_html_to io, options = {}
775
- write_format_to SaveOptions::DEFAULT_HTML, io, options
1391
+ def write_html_to(io, options = {})
1392
+ write_format_to(SaveOptions::DEFAULT_HTML, io, options)
776
1393
  end
777
1394
 
778
1395
  ###
779
1396
  # Write Node as XHTML to +io+ with +options+
780
1397
  #
781
1398
  # See Node#write_to for a list of +options+
782
- def write_xhtml_to io, options = {}
783
- write_format_to SaveOptions::DEFAULT_XHTML, io, options
1399
+ def write_xhtml_to(io, options = {})
1400
+ write_format_to(SaveOptions::DEFAULT_XHTML, io, options)
784
1401
  end
785
1402
 
786
1403
  ###
@@ -789,110 +1406,168 @@ module Nokogiri
789
1406
  # doc.write_xml_to io, :encoding => 'UTF-8'
790
1407
  #
791
1408
  # See Node#write_to for a list of options
792
- def write_xml_to io, options = {}
1409
+ def write_xml_to(io, options = {})
793
1410
  options[:save_with] ||= SaveOptions::DEFAULT_XML
794
- write_to io, options
1411
+ write_to(io, options)
795
1412
  end
796
1413
 
797
- ###
798
- # Compare two Node objects with respect to their Document. Nodes from
799
- # different documents cannot be compared.
800
- def <=> other
801
- return nil unless other.is_a?(Nokogiri::XML::Node)
802
- return nil unless document == other.document
803
- compare other
1414
+ def canonicalize(mode = XML::XML_C14N_1_0, inclusive_namespaces = nil, with_comments = false)
1415
+ c14n_root = self
1416
+ document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent|
1417
+ tn = node.is_a?(XML::Node) ? node : parent
1418
+ tn == c14n_root || tn.ancestors.include?(c14n_root)
1419
+ end
804
1420
  end
805
1421
 
806
- ###
807
- # Do xinclude substitution on the subtree below node. If given a block, a
808
- # Nokogiri::XML::ParseOptions object initialized from +options+, will be
809
- # passed to it, allowing more convenient modification of the parser options.
810
- def do_xinclude options = XML::ParseOptions::DEFAULT_XML
811
- options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
1422
+ DECONSTRUCT_KEYS = [:name, :attributes, :children, :namespace, :content, :elements, :inner_html].freeze # :nodoc:
1423
+ DECONSTRUCT_METHODS = { attributes: :attribute_nodes }.freeze # :nodoc:
812
1424
 
813
- # give options to user
814
- yield options if block_given?
815
-
816
- # call c extension
817
- process_xincludes(options.to_i)
1425
+ #
1426
+ # :call-seq: deconstruct_keys(array_of_names) Hash
1427
+ #
1428
+ # Returns a hash describing the Node, to use in pattern matching.
1429
+ #
1430
+ # Valid keys and their values:
1431
+ # - +name+ → (String) The name of this node, or "text" if it is a Text node.
1432
+ # - +namespace+ → (Namespace, nil) The namespace of this node, or nil if there is no namespace.
1433
+ # - +attributes+ → (Array<Attr>) The attributes of this node.
1434
+ # - +children+ → (Array<Node>) The children of this node. 💡 Note this includes text nodes.
1435
+ # - +elements+ → (Array<Node>) The child elements of this node. 💡 Note this does not include text nodes.
1436
+ # - +content+ → (String) The contents of all the text nodes in this node's subtree. See #content.
1437
+ # - +inner_html+ → (String) The inner markup for the children of this node. See #inner_html.
1438
+ #
1439
+ # *Example*
1440
+ #
1441
+ # doc = Nokogiri::XML.parse(<<~XML)
1442
+ # <?xml version="1.0"?>
1443
+ # <parent xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko">
1444
+ # <child1 foo="abc" noko:bar="def">First</child1>
1445
+ # <noko:child2 foo="qwe" noko:bar="rty">Second</noko:child2>
1446
+ # </parent>
1447
+ # XML
1448
+ #
1449
+ # doc.root.deconstruct_keys([:name, :namespace])
1450
+ # # => {:name=>"parent",
1451
+ # # :namespace=>
1452
+ # # #(Namespace:0x35c { href = "http://nokogiri.org/ns/default" })}
1453
+ #
1454
+ # doc.root.deconstruct_keys([:inner_html, :content])
1455
+ # # => {:content=>"\n" + " First\n" + " Second\n",
1456
+ # # :inner_html=>
1457
+ # # "\n" +
1458
+ # # " <child1 foo=\"abc\" noko:bar=\"def\">First</child1>\n" +
1459
+ # # " <noko:child2 foo=\"qwe\" noko:bar=\"rty\">Second</noko:child2>\n"}
1460
+ #
1461
+ # doc.root.elements.first.deconstruct_keys([:attributes])
1462
+ # # => {:attributes=>
1463
+ # # [#(Attr:0x370 { name = "foo", value = "abc" }),
1464
+ # # #(Attr:0x384 {
1465
+ # # name = "bar",
1466
+ # # namespace = #(Namespace:0x398 {
1467
+ # # prefix = "noko",
1468
+ # # href = "http://nokogiri.org/ns/noko"
1469
+ # # }),
1470
+ # # value = "def"
1471
+ # # })]}
1472
+ #
1473
+ # Since v1.14.0
1474
+ #
1475
+ def deconstruct_keys(keys)
1476
+ requested_keys = DECONSTRUCT_KEYS & keys
1477
+ {}.tap do |values|
1478
+ requested_keys.each do |key|
1479
+ method = DECONSTRUCT_METHODS[key] || key
1480
+ values[key] = send(method)
1481
+ end
1482
+ end
818
1483
  end
819
1484
 
820
- def canonicalize(mode=XML::XML_C14N_1_0,inclusive_namespaces=nil,with_comments=false)
821
- c14n_root = self
822
- document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent|
823
- tn = node.is_a?(XML::Node) ? node : parent
824
- tn == c14n_root || tn.ancestors.include?(c14n_root)
1485
+ # :section:
1486
+
1487
+ protected
1488
+
1489
+ def coerce(data)
1490
+ case data
1491
+ when XML::NodeSet
1492
+ return data
1493
+ when XML::DocumentFragment
1494
+ return data.children
1495
+ when String
1496
+ return fragment(data).children
1497
+ when Document, XML::Attr
1498
+ # unacceptable
1499
+ when XML::Node
1500
+ return data
825
1501
  end
1502
+
1503
+ raise ArgumentError, <<~EOERR
1504
+ Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
1505
+ (You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)
1506
+ EOERR
826
1507
  end
827
1508
 
828
1509
  private
829
1510
 
830
- def add_sibling next_or_previous, node_or_tags
831
- impl = (next_or_previous == :next) ? :add_next_sibling_node : :add_previous_sibling_node
832
- iter = (next_or_previous == :next) ? :reverse_each : :each
1511
+ def keywordify(keywords)
1512
+ case keywords
1513
+ when Enumerable
1514
+ keywords
1515
+ when String
1516
+ keywords.scan(/\S+/)
1517
+ else
1518
+ raise ArgumentError,
1519
+ "Keyword attributes must be passed as either a String or an Enumerable, but received #{keywords.class}"
1520
+ end
1521
+ end
1522
+
1523
+ def add_sibling(next_or_previous, node_or_tags)
1524
+ raise("Cannot add sibling to a node with no parent") unless parent
833
1525
 
834
- node_or_tags = coerce node_or_tags
1526
+ impl = next_or_previous == :next ? :add_next_sibling_node : :add_previous_sibling_node
1527
+ iter = next_or_previous == :next ? :reverse_each : :each
1528
+
1529
+ node_or_tags = parent.coerce(node_or_tags)
835
1530
  if node_or_tags.is_a?(XML::NodeSet)
836
1531
  if text?
837
- pivot = Nokogiri::XML::Node.new 'dummy', document
838
- send impl, pivot
1532
+ pivot = Nokogiri::XML::Node.new("dummy", document)
1533
+ send(impl, pivot)
839
1534
  else
840
1535
  pivot = self
841
1536
  end
842
- node_or_tags.send(iter) { |n| pivot.send impl, n }
1537
+ node_or_tags.send(iter) { |n| pivot.send(impl, n) }
843
1538
  pivot.unlink if text?
844
1539
  else
845
- send impl, node_or_tags
1540
+ send(impl, node_or_tags)
846
1541
  end
847
1542
  node_or_tags
848
1543
  end
849
1544
 
850
- def to_format save_option, options
851
- # FIXME: this is a hack around broken libxml versions
852
- return dump_html if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
1545
+ USING_LIBXML_WITH_BROKEN_SERIALIZATION = Nokogiri.uses_libxml?("~> 2.6.0").freeze
1546
+ private_constant :USING_LIBXML_WITH_BROKEN_SERIALIZATION
1547
+
1548
+ def to_format(save_option, options)
1549
+ return dump_html if USING_LIBXML_WITH_BROKEN_SERIALIZATION
853
1550
 
854
1551
  options[:save_with] = save_option unless options[:save_with]
855
1552
  serialize(options)
856
1553
  end
857
1554
 
858
- def write_format_to save_option, io, options
859
- # FIXME: this is a hack around broken libxml versions
860
- return (io << dump_html) if Nokogiri.uses_libxml? && %w[2 6] === LIBXML_VERSION.split('.')[0..1]
1555
+ def write_format_to(save_option, io, options)
1556
+ return (io << dump_html) if USING_LIBXML_WITH_BROKEN_SERIALIZATION
861
1557
 
862
1558
  options[:save_with] ||= save_option
863
- write_to io, options
1559
+ write_to(io, options)
864
1560
  end
865
1561
 
866
1562
  def inspect_attributes
867
1563
  [:name, :namespace, :attribute_nodes, :children]
868
1564
  end
869
1565
 
870
- def coerce data # :nodoc:
871
- case data
872
- when XML::NodeSet
873
- return data
874
- when XML::DocumentFragment
875
- return data.children
876
- when String
877
- return fragment(data).children
878
- when Document, XML::Attr
879
- # unacceptable
880
- when XML::Node
881
- return data
882
- end
883
-
884
- raise ArgumentError, <<-EOERR
885
- Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
886
- (You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().)
887
- EOERR
888
- end
889
-
890
- # @private
891
- IMPLIED_XPATH_CONTEXTS = [ './/'.freeze ].freeze # :nodoc:
1566
+ IMPLIED_XPATH_CONTEXTS = [".//"].freeze
892
1567
 
893
- def add_child_node_and_reparent_attrs node # :nodoc:
894
- add_child_node node
895
- node.attribute_nodes.find_all { |a| a.name =~ /:/ }.each do |attr_node|
1568
+ def add_child_node_and_reparent_attrs(node)
1569
+ add_child_node(node)
1570
+ node.attribute_nodes.find_all { |a| a.name.include?(":") }.each do |attr_node|
896
1571
  attr_node.remove
897
1572
  node[attr_node.name] = attr_node.value
898
1573
  end
@@ -900,3 +1575,5 @@ Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}.
900
1575
  end
901
1576
  end
902
1577
  end
1578
+
1579
+ require_relative "node/save_options"