forked from sparklemotion/nokogiri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node.rb
1572 lines (1441 loc) · 56.7 KB
/
node.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# encoding: utf-8
# frozen_string_literal: true
require "stringio"
module Nokogiri
module XML
# Nokogiri::XML::Node is the primary API you'll use to interact with your Document.
#
# == Attributes
#
# A Nokogiri::XML::Node may be treated similarly to a hash with regard to attributes. For
# example:
#
# node = Nokogiri::XML::DocumentFragment.parse("<a href='#foo' id='link'>link</a>").at_css("a")
# node.to_html # => "<a href=\"#foo\" id=\"link\">link</a>"
# node['href'] # => "#foo"
# node.keys # => ["href", "id"]
# node.values # => ["#foo", "link"]
# node['class'] = 'green' # => "green"
# node.to_html # => "<a href=\"#foo\" id=\"link\" class=\"green\">link</a>"
#
# See the method group entitled Node@Working+With+Node+Attributes for the full set of methods.
#
# == Navigation
#
# Nokogiri::XML::Node also has methods that let you move around your tree:
#
# [#parent, #children, #next, #previous]
# Navigate up, down, or through siblings.
#
# See the method group entitled Node@Traversing+Document+Structure for the full set of methods.
#
# == Serialization
#
# When printing or otherwise emitting a document or a node (and its subtree), there are a few
# methods you might want to use:
#
# [#content, #text, #inner_text, #to_str]
# These methods will all **emit plaintext**,
# meaning that entities will be replaced (e.g., +<+ will be replaced with +<+), meaning
# that any sanitizing will likely be un-done in the output.
#
# [#to_s, #to_xml, #to_html, #inner_html]
# These methods will all **emit properly-escaped markup**, meaning that it's suitable for
# consumption by browsers, parsers, etc.
#
# See the method group entitled Node@Serialization+and+Generating+Output for the full set of methods.
#
# == Searching
#
# You may search this node's subtree using methods like #xpath and #css.
#
# See the method group entitled Node@Searching+via+XPath+or+CSS+Queries for the full set of methods.
#
class Node
include Nokogiri::XML::PP::Node
include Nokogiri::XML::Searchable
include Nokogiri::ClassResolver
include Enumerable
# Element node type, see Nokogiri::XML::Node#element?
ELEMENT_NODE = 1
# Attribute node type
ATTRIBUTE_NODE = 2
# Text node type, see Nokogiri::XML::Node#text?
TEXT_NODE = 3
# CDATA node type, see Nokogiri::XML::Node#cdata?
CDATA_SECTION_NODE = 4
# Entity reference node type
ENTITY_REF_NODE = 5
# Entity node type
ENTITY_NODE = 6
# PI node type
PI_NODE = 7
# Comment node type, see Nokogiri::XML::Node#comment?
COMMENT_NODE = 8
# Document node type, see Nokogiri::XML::Node#xml?
DOCUMENT_NODE = 9
# Document type node type
DOCUMENT_TYPE_NODE = 10
# Document fragment node type
DOCUMENT_FRAG_NODE = 11
# Notation node type
NOTATION_NODE = 12
# HTML document node type, see Nokogiri::XML::Node#html?
HTML_DOCUMENT_NODE = 13
# DTD node type
DTD_NODE = 14
# Element declaration type
ELEMENT_DECL = 15
# Attribute declaration type
ATTRIBUTE_DECL = 16
# Entity declaration type
ENTITY_DECL = 17
# Namespace declaration type
NAMESPACE_DECL = 18
# XInclude start type
XINCLUDE_START = 19
# XInclude end type
XINCLUDE_END = 20
# DOCB document node type
DOCB_DOCUMENT_NODE = 21
#
# :call-seq:
# new(name, document) -> Nokogiri::XML::Node
# new(name, document) { |node| ... } -> Nokogiri::XML::Node
#
# Create a new node with +name+ that belongs to +document+.
#
# If you intend to add a node to a document tree, it's likely that you will prefer one of the
# Nokogiri::XML::Node methods like #add_child, #add_next_sibling, #replace, etc. which will
# both create an element (or subtree) and place it in the document tree.
#
# Another alternative, if you are concerned about performance, is
# Nokogiri::XML::Document#create_element which accepts additional arguments for contents or
# attributes but (like this method) avoids parsing markup.
#
# [Parameters]
# - +name+ (String)
# - +document+ (Nokogiri::XML::Document) The document to which the the returned node will belong.
# [Yields] Nokogiri::XML::Node
# [Returns] Nokogiri::XML::Node
#
def initialize(name, document)
# This is intentionally empty, and sets the method signature for subclasses.
end
###
# Decorate this node with the decorators set up in this node's Document
def decorate!
document.decorate(self)
end
# :section: Manipulating Document Structure
###
# Add +node_or_tags+ as a child of this Node.
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
# a DocumentFragment, NodeSet, or String).
#
# Also see related method +<<+.
def add_child(node_or_tags)
node_or_tags = coerce(node_or_tags)
if node_or_tags.is_a?(XML::NodeSet)
node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) }
else
add_child_node_and_reparent_attrs(node_or_tags)
end
node_or_tags
end
###
# Add +node_or_tags+ as the first child of this Node.
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
# a DocumentFragment, NodeSet, or String).
#
# Also see related method +add_child+.
def prepend_child(node_or_tags)
if (first = children.first)
# Mimic the error add_child would raise.
raise "Document already has a root node" if document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
first.__send__(:add_sibling, :previous, node_or_tags)
else
add_child(node_or_tags)
end
end
# :call-seq:
# wrap(markup) -> self
# wrap(node) -> self
#
# Wrap this Node with the node parsed from +markup+ or a dup of the +node+.
#
# [Parameters]
# - *markup* (String)
# Markup that is parsed and used as the wrapper. This node's parent, if it exists, is used
# as the context node for parsing; otherwise the associated document is used. If the parsed
# fragment has multiple roots, the first root node is used as the wrapper.
# - *node* (Nokogiri::XML::Node)
# An element that is `#dup`ed and used as the wrapper.
#
# [Returns] +self+, to support chaining.
#
# Also see NodeSet#wrap
#
# *Example* with a +String+ argument:
#
# doc = Nokogiri::HTML5(<<~HTML)
# <html><body>
# <a>asdf</a>
# </body></html>
# HTML
# doc.at_css("a").wrap("<div></div>")
# doc.to_html
# # => <html><head></head><body>
# # <div><a>asdf</a></div>
# # </body></html>
#
# *Example* with a +Node+ argument:
#
# doc = Nokogiri::HTML5(<<~HTML)
# <html><body>
# <a>asdf</a>
# </body></html>
# HTML
# doc.at_css("a").wrap(doc.create_element("div"))
# doc.to_html
# # <html><head></head><body>
# # <div><a>asdf</a></div>
# # </body></html>
#
def wrap(node_or_tags)
case node_or_tags
when String
context_node = parent || document
new_parent = context_node.coerce(node_or_tags).first
if new_parent.nil?
raise "Failed to parse '#{node_or_tags}' in the context of a '#{context_node.name}' element"
end
when XML::Node
new_parent = node_or_tags.dup
else
raise ArgumentError, "Requires a String or Node argument, and cannot accept a #{node_or_tags.class}"
end
if parent
add_next_sibling(new_parent)
else
new_parent.unlink
end
new_parent.add_child(self)
self
end
###
# Add +node_or_tags+ as a child of this Node.
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns +self+, to support chaining of calls (e.g., root << child1 << child2)
#
# Also see related method +add_child+.
def <<(node_or_tags)
add_child(node_or_tags)
self
end
###
# Insert +node_or_tags+ before this Node (as a sibling).
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
# a DocumentFragment, NodeSet, or String).
#
# Also see related method +before+.
def add_previous_sibling(node_or_tags)
raise ArgumentError,
"A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
add_sibling(:previous, node_or_tags)
end
###
# Insert +node_or_tags+ after this Node (as a sibling).
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
# a DocumentFragment, NodeSet, or String).
#
# Also see related method +after+.
def add_next_sibling(node_or_tags)
raise ArgumentError,
"A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?)
add_sibling(:next, node_or_tags)
end
####
# Insert +node_or_tags+ before this node (as a sibling).
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns +self+, to support chaining of calls.
#
# Also see related method +add_previous_sibling+.
def before(node_or_tags)
add_previous_sibling(node_or_tags)
self
end
####
# Insert +node_or_tags+ after this node (as a sibling).
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a String
# containing markup.
#
# Returns +self+, to support chaining of calls.
#
# Also see related method +add_next_sibling+.
def after(node_or_tags)
add_next_sibling(node_or_tags)
self
end
####
# Set the content for this Node to +node_or_tags+.
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a String
# containing markup.
#
# ⚠ Please note that despite the name, this method will *not* always parse a String argument
# as HTML. A String argument will be parsed with the +DocumentFragment+ parser related to this
# node's document.
#
# For example, if the document is an HTML4::Document then the string will be parsed as HTML4
# using HTML4::DocumentFragment; but if the document is an XML::Document then it will
# parse the string as XML using XML::DocumentFragment.
#
# Also see related method +children=+
def inner_html=(node_or_tags)
self.children = node_or_tags
end
####
# Set the content for this Node +node_or_tags+
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a Nokogiri::XML::DocumentFragment, or a String
# containing markup.
#
# Also see related method +inner_html=+
def children=(node_or_tags)
node_or_tags = coerce(node_or_tags)
children.unlink
if node_or_tags.is_a?(XML::NodeSet)
node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) }
else
add_child_node_and_reparent_attrs(node_or_tags)
end
end
####
# Replace this Node with +node_or_tags+.
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# containing markup.
#
# Returns the reparented node (if +node_or_tags+ is a Node), or NodeSet (if +node_or_tags+ is
# a DocumentFragment, NodeSet, or String).
#
# Also see related method +swap+.
def replace(node_or_tags)
raise("Cannot replace a node with no parent") unless parent
# We cannot replace a text node directly, otherwise libxml will return
# an internal error at parser.c:13031, I don't know exactly why
# libxml is trying to find a parent node that is an element or document
# so I can't tell if this is bug in libxml or not. issue #775.
if text?
replacee = Nokogiri::XML::Node.new("dummy", document)
add_previous_sibling_node(replacee)
unlink
return replacee.replace(node_or_tags)
end
node_or_tags = parent.coerce(node_or_tags)
if node_or_tags.is_a?(XML::NodeSet)
node_or_tags.each { |n| add_previous_sibling(n) }
unlink
else
replace_node(node_or_tags)
end
node_or_tags
end
####
# Swap this Node for +node_or_tags+
#
# +node_or_tags+ can be a Nokogiri::XML::Node, a ::DocumentFragment, a ::NodeSet, or a String
# Containing markup.
#
# Returns self, to support chaining of calls.
#
# Also see related method +replace+.
def swap(node_or_tags)
replace(node_or_tags)
self
end
####
# Set the Node's content to a Text node containing +string+. The string gets XML escaped, not
# interpreted as markup.
def content=(string)
self.native_content = encode_special_chars(string.to_s)
end
###
# Set the parent Node for this Node
def parent=(parent_node)
parent_node.add_child(self)
end
###
# Adds a default namespace supplied as a string +url+ href, to self.
# The consequence is as an xmlns attribute with supplied argument were
# present in parsed XML. A default namespace set with this method will
# now show up in #attributes, but when this node is serialized to XML an
# "xmlns" attribute will appear. See also #namespace and #namespace=
def default_namespace=(url)
add_namespace_definition(nil, url)
end
###
# Set the default namespace on this node (as would be defined with an
# "xmlns=" attribute in XML source), as a Namespace object +ns+. Note that
# a Namespace added this way will NOT be serialized as an xmlns attribute
# for this node. You probably want #default_namespace= instead, or perhaps
# #add_namespace_definition with a nil prefix argument.
def namespace=(ns)
return set_namespace(ns) unless ns
unless Nokogiri::XML::Namespace === ns
raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace"
end
if ns.document != document
raise ArgumentError, "namespace must be declared on the same document"
end
set_namespace(ns)
end
###
# Do xinclude substitution on the subtree below node. If given a block, a
# Nokogiri::XML::ParseOptions object initialized from +options+, will be
# passed to it, allowing more convenient modification of the parser options.
def do_xinclude(options = XML::ParseOptions::DEFAULT_XML)
options = Nokogiri::XML::ParseOptions.new(options) if Integer === options
yield options if block_given?
# call c extension
process_xincludes(options.to_i)
end
alias_method :next, :next_sibling
alias_method :previous, :previous_sibling
alias_method :next=, :add_next_sibling
alias_method :previous=, :add_previous_sibling
alias_method :remove, :unlink
alias_method :name=, :node_name=
alias_method :add_namespace, :add_namespace_definition
# :section:
alias_method :inner_text, :content
alias_method :text, :content
alias_method :to_str, :content
alias_method :name, :node_name
alias_method :type, :node_type
alias_method :clone, :dup
alias_method :elements, :element_children
# :section: Working With Node Attributes
# :call-seq: [](name) → (String, nil)
#
# Fetch an attribute from this node.
#
# ⚠ Note that attributes with namespaces cannot be accessed with this method. To access
# namespaced attributes, use #attribute_with_ns.
#
# [Returns] (String, nil) value of the attribute +name+, or +nil+ if no matching attribute exists
#
# *Example*
#
# doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
# child = doc.at_css("child")
# child["size"] # => "large"
# child["class"] # => "big wide tall"
#
# *Example:* Namespaced attributes will not be returned.
#
# ⚠ Note namespaced attributes may be accessed with #attribute or #attribute_with_ns
#
# doc = Nokogiri::XML(<<~EOF)
# <root xmlns:width='http://example.com/widths'>
# <child width:size='broad'/>
# </root>
# EOF
# doc.at_css("child")["size"] # => nil
# doc.at_css("child").attribute("size").value # => "broad"
# doc.at_css("child").attribute_with_ns("size", "http://example.com/widths").value
# # => "broad"
#
def [](name)
get(name.to_s)
end
# :call-seq: []=(name, value) → value
#
# Update the attribute +name+ to +value+, or create the attribute if it does not exist.
#
# ⚠ Note that attributes with namespaces cannot be accessed with this method. To access
# namespaced attributes for update, use #attribute_with_ns. To add a namespaced attribute,
# see the example below.
#
# [Returns] +value+
#
# *Example*
#
# doc = Nokogiri::XML("<root><child/></root>")
# child = doc.at_css("child")
# child["size"] = "broad"
# child.to_html
# # => "<child size=\"broad\"></child>"
#
# *Example:* Add a namespaced attribute.
#
# doc = Nokogiri::XML(<<~EOF)
# <root xmlns:width='http://example.com/widths'>
# <child/>
# </root>
# EOF
# child = doc.at_css("child")
# child["size"] = "broad"
# ns = doc.root.namespace_definitions.find { |ns| ns.prefix == "width" }
# child.attribute("size").namespace = ns
# doc.to_html
# # => "<root xmlns:width=\"http://example.com/widths\">\n" +
# # " <child width:size=\"broad\"></child>\n" +
# # "</root>\n"
#
def []=(name, value)
set(name.to_s, value.to_s)
end
#
# :call-seq: attributes() → Hash<String ⇒ Nokogiri::XML::Attr>
#
# Fetch this node's attributes.
#
# ⚠ Because the keys do not include any namespace information for the attribute, in case of a
# simple name collision, not all attributes will be returned. In this case, you will need to
# use #attribute_nodes.
#
# [Returns]
# Hash containing attributes belonging to +self+. The hash keys are String attribute
# names (without the namespace), and the hash values are Nokogiri::XML::Attr.
#
# *Example* with no namespaces:
#
# doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>")
# doc.at_css("child").attributes
# # => {"size"=>#(Attr:0x550 { name = "size", value = "large" }),
# # "class"=>#(Attr:0x564 { name = "class", value = "big wide tall" })}
#
# *Example* with a namespace:
#
# doc = Nokogiri::XML("<root xmlns:desc='http://example.com/sizes'><child desc:size='large'/></root>")
# doc.at_css("child").attributes
# # => {"size"=>
# # #(Attr:0x550 {
# # name = "size",
# # namespace = #(Namespace:0x564 {
# # prefix = "desc",
# # href = "http://example.com/sizes"
# # }),
# # value = "large"
# # })}
#
# *Example* with an attribute name collision:
#
# ⚠ Note that only one of the attributes is returned in the Hash.
#
# doc = Nokogiri::XML(<<~EOF)
# <root xmlns:width='http://example.com/widths'
# xmlns:height='http://example.com/heights'>
# <child width:size='broad' height:size='tall'/>
# </root>
# EOF
# doc.at_css("child").attributes
# # => {"size"=>
# # #(Attr:0x550 {
# # name = "size",
# # namespace = #(Namespace:0x564 {
# # prefix = "height",
# # href = "http://example.com/heights"
# # }),
# # value = "tall"
# # })}
#
def attributes
attribute_nodes.each_with_object({}) do |node, hash|
hash[node.node_name] = node
end
end
###
# Get the attribute values for this Node.
def values
attribute_nodes.map(&:value)
end
###
# Does this Node's attributes include <value>
def value?(value)
values.include?(value)
end
###
# Get the attribute names for this Node.
def keys
attribute_nodes.map(&:node_name)
end
###
# Iterate over each attribute name and value pair for this Node.
def each
attribute_nodes.each do |node|
yield [node.node_name, node.value]
end
end
###
# Remove the attribute named +name+
def remove_attribute(name)
attr = attributes[name].remove if key?(name)
clear_xpath_context if Nokogiri.jruby?
attr
end
#
# :call-seq: classes() → Array<String>
#
# Fetch CSS class names of a Node.
#
# This is a convenience function and is equivalent to:
#
# node.kwattr_values("class")
#
# See related: #kwattr_values, #add_class, #append_class, #remove_class
#
# [Returns]
# The CSS classes (Array of String) present in the Node's "class" attribute. If the
# attribute is empty or non-existent, the return value is an empty array.
#
# *Example*
#
# node # => <div class="section title header"></div>
# node.classes # => ["section", "title", "header"]
#
def classes
kwattr_values("class")
end
#
# :call-seq: add_class(names) → self
#
# Ensure HTML CSS classes are present on +self+. Any CSS classes in +names+ that already exist
# in the "class" attribute are _not_ added. Note that any existing duplicates in the
# "class" attribute are not removed. Compare with #append_class.
#
# This is a convenience function and is equivalent to:
#
# node.kwattr_add("class", names)
#
# See related: #kwattr_add, #classes, #append_class, #remove_class
#
# [Parameters]
# - +names+ (String, Array<String>)
#
# CSS class names to be added to the Node's "class" attribute. May be a string containing
# whitespace-delimited names, or an Array of String names. Any class names already present
# will not be added. Any class names not present will be added. If no "class" attribute
# exists, one is created.
#
# [Returns] +self+ (Node) for ease of chaining method calls.
#
# *Example:* Ensure that the node has CSS class "section"
#
# node # => <div></div>
# node.add_class("section") # => <div class="section"></div>
# node.add_class("section") # => <div class="section"></div> # duplicate not added
#
# *Example:* Ensure that the node has CSS classes "section" and "header", via a String argument
#
# Note that the CSS class "section" is not added because it is already present.
# Note also that the pre-existing duplicate CSS class "section" is not removed.
#
# node # => <div class="section section"></div>
# node.add_class("section header") # => <div class="section section header"></div>
#
# *Example:* Ensure that the node has CSS classes "section" and "header", via an Array argument
#
# node # => <div></div>
# node.add_class(["section", "header"]) # => <div class="section header"></div>
#
def add_class(names)
kwattr_add("class", names)
end
#
# :call-seq: append_class(names) → self
#
# Add HTML CSS classes to +self+, regardless of duplication. Compare with #add_class.
#
# This is a convenience function and is equivalent to:
#
# node.kwattr_append("class", names)
#
# See related: #kwattr_append, #classes, #add_class, #remove_class
#
# [Parameters]
# - +names+ (String, Array<String>)
#
# CSS class names to be appended to the Node's "class" attribute. May be a string containing
# whitespace-delimited names, or an Array of String names. All class names passed in will be
# appended to the "class" attribute even if they are already present in the attribute
# value. If no "class" attribute exists, one is created.
#
# [Returns] +self+ (Node) for ease of chaining method calls.
#
# *Example:* Append "section" to the node's CSS "class" attribute
#
# node # => <div></div>
# node.append_class("section") # => <div class="section"></div>
# node.append_class("section") # => <div class="section section"></div> # duplicate added!
#
# *Example:* Append "section" and "header" to the noded's CSS "class" attribute, via a String argument
#
# Note that the CSS class "section" is appended even though it is already present
#
# node # => <div class="section section"></div>
# node.append_class("section header") # => <div class="section section section header"></div>
#
# *Example:* Append "section" and "header" to the node's CSS "class" attribute, via an Array argument
#
# node # => <div></div>
# node.append_class(["section", "header"]) # => <div class="section header"></div>
# node.append_class(["section", "header"]) # => <div class="section header section header"></div>
#
def append_class(names)
kwattr_append("class", names)
end
# :call-seq:
# remove_class(css_classes) → self
#
# Remove HTML CSS classes from this node. Any CSS class names in +css_classes+ that exist in
# this node's "class" attribute are removed, including any multiple entries.
#
# If no CSS classes remain after this operation, or if +css_classes+ is +nil+, the "class"
# attribute is deleted from the node.
#
# This is a convenience function and is equivalent to:
#
# node.kwattr_remove("class", css_classes)
#
# Also see #kwattr_remove, #classes, #add_class, #append_class
#
# [Parameters]
# - +css_classes+ (String, Array<String>)
#
# CSS class names to be removed from the Node's
# "class" attribute. May be a string containing whitespace-delimited names, or an Array of
# String names. Any class names already present will be removed. If no CSS classes remain,
# the "class" attribute is deleted.
#
# [Returns] +self+ (Nokogiri::XML::Node) for ease of chaining method calls.
#
# *Example*: Deleting a CSS class
#
# Note that all instances of the class "section" are removed from the "class" attribute.
#
# node # => <div class="section header section"></div>
# node.remove_class("section") # => <div class="header"></div>
#
# *Example*: Deleting the only remaining CSS class
#
# Note that the attribute is removed once there are no remaining classes.
#
# node # => <div class="section"></div>
# node.remove_class("section") # => <div></div>
#
# *Example*: Deleting multiple CSS classes
#
# Note that the "class" attribute is deleted once it's empty.
#
# node # => <div class="section header float"></div>
# node.remove_class(["section", "float"]) # => <div class="header"></div>
#
def remove_class(names = nil)
kwattr_remove("class", names)
end
# :call-seq:
# kwattr_values(attribute_name) → Array<String>
#
# Fetch values from a keyword attribute of a Node.
#
# A "keyword attribute" is a node attribute that contains a set of space-delimited
# values. Perhaps the most familiar example of this is the HTML "class" attribute used to
# contain CSS classes. But other keyword attributes exist, for instance
# {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
#
# See also #classes, #kwattr_add, #kwattr_append, #kwattr_remove
#
# [Parameters]
# - +attribute_name+ (String) The name of the keyword attribute to be inspected.
#
# [Returns]
# (Array<String>) The values present in the Node's +attribute_name+ attribute. If the
# attribute is empty or non-existent, the return value is an empty array.
#
# *Example:*
#
# node # => <a rel="nofollow noopener external">link</a>
# node.kwattr_values("rel") # => ["nofollow", "noopener", "external"]
#
# Since v1.11.0
def kwattr_values(attribute_name)
keywordify(get_attribute(attribute_name) || [])
end
# :call-seq:
# kwattr_add(attribute_name, keywords) → self
#
# Ensure that values are present in a keyword attribute.
#
# Any values in +keywords+ that already exist in the Node's attribute values are _not_
# added. Note that any existing duplicates in the attribute values are not removed. Compare
# with #kwattr_append.
#
# A "keyword attribute" is a node attribute that contains a set of space-delimited
# values. Perhaps the most familiar example of this is the HTML "class" attribute used to
# contain CSS classes. But other keyword attributes exist, for instance
# {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
#
# See also #add_class, #kwattr_values, #kwattr_append, #kwattr_remove
#
# [Parameters]
# - +attribute_name+ (String) The name of the keyword attribute to be modified.
# - +keywords+ (String, Array<String>)
# Keywords to be added to the attribute named +attribute_name+. May be a string containing
# whitespace-delimited values, or an Array of String values. Any values already present will
# not be added. Any values not present will be added. If the named attribute does not exist,
# it is created.
#
# [Returns] +self+ (Nokogiri::XML::Node) for ease of chaining method calls.
#
# *Example:* Ensure that a +Node+ has "nofollow" in its +rel+ attribute.
#
# Note that duplicates are not added.
#
# node # => <a></a>
# node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a>
# node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a>
#
# *Example:* Ensure that a +Node+ has "nofollow" and "noreferrer" in its +rel+ attribute, via a
# String argument.
#
# Note that "nofollow" is not added because it is already present. Note also that the
# pre-existing duplicate "nofollow" is not removed.
#
# node # => <a rel="nofollow nofollow"></a>
# node.kwattr_add("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a>
#
# *Example:* Ensure that a +Node+ has "nofollow" and "noreferrer" in its +rel+ attribute, via
# an Array argument.
#
# node # => <a></a>
# node.kwattr_add("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a>
#
# Since v1.11.0
def kwattr_add(attribute_name, keywords)
keywords = keywordify(keywords)
current_kws = kwattr_values(attribute_name)
new_kws = (current_kws + (keywords - current_kws)).join(" ")
set_attribute(attribute_name, new_kws)
self
end
# :call-seq:
# kwattr_append(attribute_name, keywords) → self
#
# Add keywords to a Node's keyword attribute, regardless of duplication. Compare with
# #kwattr_add.
#
# A "keyword attribute" is a node attribute that contains a set of space-delimited
# values. Perhaps the most familiar example of this is the HTML "class" attribute used to
# contain CSS classes. But other keyword attributes exist, for instance
# {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
#
# See also #append_class, #kwattr_values, #kwattr_add, #kwattr_remove
#
# [Parameters]
# - +attribute_name+ (String) The name of the keyword attribute to be modified.
# - +keywords+ (String, Array<String>)
# Keywords to be added to the attribute named +attribute_name+. May be a string containing
# whitespace-delimited values, or an Array of String values. All values passed in will be
# appended to the named attribute even if they are already present in the attribute. If the
# named attribute does not exist, it is created.
#
# [Returns] +self+ (Node) for ease of chaining method calls.
#
# *Example:* Append "nofollow" to the +rel+ attribute.
#
# Note that duplicates are added.
#
# node # => <a></a>
# node.kwattr_append("rel", "nofollow") # => <a rel="nofollow"></a>
# node.kwattr_append("rel", "nofollow") # => <a rel="nofollow nofollow"></a>
#
# *Example:* Append "nofollow" and "noreferrer" to the +rel+ attribute, via a String argument.
#
# Note that "nofollow" is appended even though it is already present.
#
# node # => <a rel="nofollow"></a>
# node.kwattr_append("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a>
#
#
# *Example:* Append "nofollow" and "noreferrer" to the +rel+ attribute, via an Array argument.
#
# node # => <a></a>
# node.kwattr_append("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a>
#
# Since v1.11.0
def kwattr_append(attribute_name, keywords)
keywords = keywordify(keywords)
current_kws = kwattr_values(attribute_name)
new_kws = (current_kws + keywords).join(" ")
set_attribute(attribute_name, new_kws)
self
end
# :call-seq:
# kwattr_remove(attribute_name, keywords) → self
#
# Remove keywords from a keyword attribute. Any matching keywords that exist in the named
# attribute are removed, including any multiple entries.
#
# If no keywords remain after this operation, or if +keywords+ is +nil+, the attribute is
# deleted from the node.
#
# A "keyword attribute" is a node attribute that contains a set of space-delimited
# values. Perhaps the most familiar example of this is the HTML "class" attribute used to
# contain CSS classes. But other keyword attributes exist, for instance
# {the "rel" attribute}[https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel].
#
# See also #remove_class, #kwattr_values, #kwattr_add, #kwattr_append
#
# [Parameters]
# - +attribute_name+ (String) The name of the keyword attribute to be modified.
# - +keywords+ (String, Array<String>)
# Keywords to be removed from the attribute named +attribute_name+. May be a string
# containing whitespace-delimited values, or an Array of String values. Any keywords present
# in the named attribute will be removed. If no keywords remain, or if +keywords+ is nil,
# the attribute is deleted.
#
# [Returns] +self+ (Node) for ease of chaining method calls.
#
# *Example:*
#
# Note that the +rel+ attribute is deleted when empty.
#
# node # => <a rel="nofollow noreferrer">link</a>
# node.kwattr_remove("rel", "nofollow") # => <a rel="noreferrer">link</a>
# node.kwattr_remove("rel", "noreferrer") # => <a>link</a>
#
# Since v1.11.0
def kwattr_remove(attribute_name, keywords)
if keywords.nil?
remove_attribute(attribute_name)
return self
end
keywords = keywordify(keywords)
current_kws = kwattr_values(attribute_name)
new_kws = current_kws - keywords
if new_kws.empty?
remove_attribute(attribute_name)
else
set_attribute(attribute_name, new_kws.join(" "))