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
|
package org.jsoup.nodes;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jsoup.helper.StringUtil;
import org.jsoup.helper.Validate;
import org.jsoup.parser.Parser;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;
/**
* The base, abstract Node model. Elements, Documents, Comments etc are all Node
* instances.
*
* @author Jonathan Hedley, jonathan@hedley.net
*/
public abstract class Node implements Cloneable {
Node parentNode;
List<Node> childNodes;
Attributes attributes;
String baseUri;
int siblingIndex;
/**
* Create a new Node.
*
* @param baseUri
* base URI
* @param attributes
* attributes (not null, but may be empty)
*/
protected Node(String baseUri, Attributes attributes) {
Validate.notNull(baseUri);
Validate.notNull(attributes);
childNodes = new ArrayList<Node>(4);
this.baseUri = baseUri.trim();
this.attributes = attributes;
}
protected Node(String baseUri) {
this(baseUri, new Attributes());
}
/**
* Default constructor. Doesn't setup base uri, children, or attributes; use
* with caution.
*/
protected Node() {
childNodes = Collections.emptyList();
attributes = null;
}
/**
* Get the node name of this node. Use for debugging purposes and not logic
* switching (for that, use instanceof).
*
* @return node name
*/
public abstract String nodeName();
/**
* Get an attribute's value by its key.
* <p/>
* To get an absolute URL from an attribute that may be a relative URL,
* prefix the key with <code><b>abs</b></code>, which is a shortcut to the
* {@link #absUrl} method. E.g.: <blockquote>
* <code>String url = a.attr("abs:href");</code></blockquote>
*
* @param attributeKey
* The attribute key.
* @return The attribute, or empty string if not present (to avoid nulls).
* @see #attributes()
* @see #hasAttr(String)
* @see #absUrl(String)
*/
public String attr(String attributeKey) {
Validate.notNull(attributeKey);
if (attributes.hasKey(attributeKey)) {
return attributes.get(attributeKey);
} else if (attributeKey.toLowerCase().startsWith("abs:")) {
return absUrl(attributeKey.substring("abs:".length()));
} else {
return "";
}
}
/**
* Get all of the element's attributes.
*
* @return attributes (which implements iterable, in same order as presented
* in original HTML).
*/
public Attributes attributes() {
return attributes;
}
/**
* Set an attribute (key=value). If the attribute already exists, it is
* replaced.
*
* @param attributeKey
* The attribute key.
* @param attributeValue
* The attribute value.
* @return this (for chaining)
*/
public Node attr(String attributeKey, String attributeValue) {
attributes.put(attributeKey, attributeValue);
return this;
}
/**
* Test if this element has an attribute.
*
* @param attributeKey
* The attribute key to check.
* @return true if the attribute exists, false if not.
*/
public boolean hasAttr(String attributeKey) {
Validate.notNull(attributeKey);
if (attributeKey.toLowerCase().startsWith("abs:")) {
String key = attributeKey.substring("abs:".length());
if (attributes.hasKey(key) && !absUrl(key).equals("")) {
return true;
}
}
return attributes.hasKey(attributeKey);
}
/**
* Remove an attribute from this element.
*
* @param attributeKey
* The attribute to remove.
* @return this (for chaining)
*/
public Node removeAttr(String attributeKey) {
Validate.notNull(attributeKey);
attributes.remove(attributeKey);
return this;
}
/**
* Get the base URI of this node.
*
* @return base URI
*/
public String baseUri() {
return baseUri;
}
/**
* Update the base URI of this node and all of its descendants.
*
* @param baseUri
* base URI to set
*/
public void setBaseUri(final String baseUri) {
Validate.notNull(baseUri);
traverse(new NodeVisitor() {
@Override
public void head(Node node, int depth) {
node.baseUri = baseUri;
}
@Override
public void tail(Node node, int depth) {
}
});
}
/**
* Get an absolute URL from a URL attribute that may be relative (i.e. an
* <code><a href></code> or <code><img src></code>).
* <p/>
* E.g.: <code>String absUrl = linkEl.absUrl("href");</code>
* <p/>
* If the attribute value is already absolute (i.e. it starts with a
* protocol, like <code>http://</code> or <code>https://</code> etc), and it
* successfully parses as a URL, the attribute is returned directly.
* Otherwise, it is treated as a URL relative to the element's
* {@link #baseUri}, and made absolute using that.
* <p/>
* As an alternate, you can use the {@link #attr} method with the
* <code>abs:</code> prefix, e.g.:
* <code>String absUrl = linkEl.attr("abs:href");</code>
*
* @param attributeKey
* The attribute key
* @return An absolute URL if one could be made, or an empty string (not
* null) if the attribute was missing or could not be made
* successfully into a URL.
* @see #attr
* @see java.net.URL#URL(java.net.URL, String)
*/
public String absUrl(String attributeKey) {
Validate.notEmpty(attributeKey);
String relUrl = attr(attributeKey);
if (!hasAttr(attributeKey)) {
return ""; // nothing to make absolute with
} else {
URL base;
try {
try {
base = new URL(baseUri);
} catch (MalformedURLException e) {
// the base is unsuitable, but the attribute may be abs on
// its own, so try that
URL abs = new URL(relUrl);
return abs.toExternalForm();
}
// workaround: java resolves '//path/file + ?foo' to
// '//path/?foo', not '//path/file?foo' as desired
if (relUrl.startsWith("?")) {
relUrl = base.getPath() + relUrl;
}
URL abs = new URL(base, relUrl);
return abs.toExternalForm();
} catch (MalformedURLException e) {
return "";
}
}
}
/**
* Get a child node by index
*
* @param index
* index of child node
* @return the child node at this index.
*/
public Node childNode(int index) {
return childNodes.get(index);
}
/**
* Get this node's children. Presented as an unmodifiable list: new children
* can not be added, but the child nodes themselves can be manipulated.
*
* @return list of children. If no children, returns an empty list.
*/
public List<Node> childNodes() {
return Collections.unmodifiableList(childNodes);
}
protected Node[] childNodesAsArray() {
return childNodes.toArray(new Node[childNodes().size()]);
}
/**
* Gets this node's parent node.
*
* @return parent node; or null if no parent.
*/
public Node parent() {
return parentNode;
}
/**
* Gets the Document associated with this Node.
*
* @return the Document associated with this Node, or null if there is no
* such Document.
*/
public Document ownerDocument() {
if (this instanceof Document) {
return (Document) this;
} else if (parentNode == null) {
return null;
} else {
return parentNode.ownerDocument();
}
}
/**
* Remove (delete) this node from the DOM tree. If this node has children,
* they are also removed.
*/
public void remove() {
Validate.notNull(parentNode);
parentNode.removeChild(this);
}
/**
* Insert the specified HTML into the DOM before this node (i.e. as a
* preceding sibling).
*
* @param html
* HTML to add before this node
* @return this node, for chaining
* @see #after(String)
*/
public Node before(String html) {
addSiblingHtml(siblingIndex(), html);
return this;
}
/**
* Insert the specified node into the DOM before this node (i.e. as a
* preceding sibling).
*
* @param node
* to add before this node
* @return this node, for chaining
* @see #after(Node)
*/
public Node before(Node node) {
Validate.notNull(node);
Validate.notNull(parentNode);
parentNode.addChildren(siblingIndex(), node);
return this;
}
/**
* Insert the specified HTML into the DOM after this node (i.e. as a
* following sibling).
*
* @param html
* HTML to add after this node
* @return this node, for chaining
* @see #before(String)
*/
public Node after(String html) {
addSiblingHtml(siblingIndex() + 1, html);
return this;
}
/**
* Insert the specified node into the DOM after this node (i.e. as a
* following sibling).
*
* @param node
* to add after this node
* @return this node, for chaining
* @see #before(Node)
*/
public Node after(Node node) {
Validate.notNull(node);
Validate.notNull(parentNode);
parentNode.addChildren(siblingIndex() + 1, node);
return this;
}
private void addSiblingHtml(int index, String html) {
Validate.notNull(html);
Validate.notNull(parentNode);
Element context = parent() instanceof Element ? (Element) parent()
: null;
List<Node> nodes = Parser.parseFragment(html, context, baseUri());
parentNode.addChildren(index, nodes.toArray(new Node[nodes.size()]));
}
/**
* Wrap the supplied HTML around this node.
*
* @param html
* HTML to wrap around this element, e.g.
* {@code <div class="head"></div>}. Can be arbitrarily deep.
* @return this node, for chaining.
*/
public Node wrap(String html) {
Validate.notEmpty(html);
Element context = parent() instanceof Element ? (Element) parent()
: null;
List<Node> wrapChildren = Parser
.parseFragment(html, context, baseUri());
Node wrapNode = wrapChildren.get(0);
if (wrapNode == null || !(wrapNode instanceof Element)) {
return null;
}
Element wrap = (Element) wrapNode;
Element deepest = getDeepChild(wrap);
parentNode.replaceChild(this, wrap);
deepest.addChildren(this);
// remainder (unbalanced wrap, like <div></div><p></p> -- The <p> is
// remainder
if (wrapChildren.size() > 0) {
for (int i = 0; i < wrapChildren.size(); i++) {
Node remainder = wrapChildren.get(i);
remainder.parentNode.removeChild(remainder);
wrap.appendChild(remainder);
}
}
return this;
}
/**
* Removes this node from the DOM, and moves its children up into the node's
* parent. This has the effect of dropping the node but keeping its
* children.
* <p/>
* For example, with the input html:<br/>
* {@code <div>One <span>Two <b>Three</b></span></div>}<br/>
* Calling {@code element.unwrap()} on the {@code span} element will result
* in the html:<br/>
* {@code <div>One Two <b>Three</b></div>}<br/>
* and the {@code "Two "} {@link TextNode} being returned.
*
* @return the first child of this node, after the node has been unwrapped.
* Null if the node had no children.
* @see #remove()
* @see #wrap(String)
*/
public Node unwrap() {
Validate.notNull(parentNode);
int index = siblingIndex;
Node firstChild = childNodes.size() > 0 ? childNodes.get(0) : null;
parentNode.addChildren(index, childNodesAsArray());
remove();
return firstChild;
}
private Element getDeepChild(Element el) {
List<Element> children = el.children();
if (children.size() > 0) {
return getDeepChild(children.get(0));
} else {
return el;
}
}
/**
* Replace this node in the DOM with the supplied node.
*
* @param in
* the node that will will replace the existing node.
*/
public void replaceWith(Node in) {
Validate.notNull(in);
Validate.notNull(parentNode);
parentNode.replaceChild(this, in);
}
protected void setParentNode(Node parentNode) {
if (this.parentNode != null) {
this.parentNode.removeChild(this);
}
this.parentNode = parentNode;
}
protected void replaceChild(Node out, Node in) {
Validate.isTrue(out.parentNode == this);
Validate.notNull(in);
if (in.parentNode != null) {
in.parentNode.removeChild(in);
}
Integer index = out.siblingIndex();
childNodes.set(index, in);
in.parentNode = this;
in.setSiblingIndex(index);
out.parentNode = null;
}
protected void removeChild(Node out) {
Validate.isTrue(out.parentNode == this);
int index = out.siblingIndex();
childNodes.remove(index);
reindexChildren();
out.parentNode = null;
}
protected void addChildren(Node... children) {
// most used. short circuit addChildren(int), which hits reindex
// children and array copy
for (Node child : children) {
reparentChild(child);
childNodes.add(child);
child.setSiblingIndex(childNodes.size() - 1);
}
}
protected void addChildren(int index, Node... children) {
Validate.noNullElements(children);
for (int i = children.length - 1; i >= 0; i--) {
Node in = children[i];
reparentChild(in);
childNodes.add(index, in);
}
reindexChildren();
}
private void reparentChild(Node child) {
if (child.parentNode != null) {
child.parentNode.removeChild(child);
}
child.setParentNode(this);
}
private void reindexChildren() {
for (int i = 0; i < childNodes.size(); i++) {
childNodes.get(i).setSiblingIndex(i);
}
}
/**
* Retrieves this node's sibling nodes. Similar to {@link #childNodes()
* node.parent.childNodes()}, but does not include this node (a node is not
* a sibling of itself).
*
* @return node siblings. If the node has no parent, returns an empty list.
*/
public List<Node> siblingNodes() {
if (parentNode == null) {
return Collections.emptyList();
}
List<Node> nodes = parentNode.childNodes;
List<Node> siblings = new ArrayList<Node>(nodes.size() - 1);
for (Node node : nodes) {
if (node != this) {
siblings.add(node);
}
}
return siblings;
}
/**
* Get this node's next sibling.
*
* @return next sibling, or null if this is the last sibling
*/
public Node nextSibling() {
if (parentNode == null) {
return null; // root
}
List<Node> siblings = parentNode.childNodes;
Integer index = siblingIndex();
Validate.notNull(index);
if (siblings.size() > index + 1) {
return siblings.get(index + 1);
} else {
return null;
}
}
/**
* Get this node's previous sibling.
*
* @return the previous sibling, or null if this is the first sibling
*/
public Node previousSibling() {
if (parentNode == null) {
return null; // root
}
List<Node> siblings = parentNode.childNodes;
Integer index = siblingIndex();
Validate.notNull(index);
if (index > 0) {
return siblings.get(index - 1);
} else {
return null;
}
}
/**
* Get the list index of this node in its node sibling list. I.e. if this is
* the first node sibling, returns 0.
*
* @return position in node sibling list
* @see org.jsoup.nodes.Element#elementSiblingIndex()
*/
public int siblingIndex() {
return siblingIndex;
}
protected void setSiblingIndex(int siblingIndex) {
this.siblingIndex = siblingIndex;
}
/**
* Perform a depth-first traversal through this node and its descendants.
*
* @param nodeVisitor
* the visitor callbacks to perform on each node
* @return this node, for chaining
*/
public Node traverse(NodeVisitor nodeVisitor) {
Validate.notNull(nodeVisitor);
NodeTraversor traversor = new NodeTraversor(nodeVisitor);
traversor.traverse(this);
return this;
}
/**
* Get the outer HTML of this node.
*
* @return HTML
*/
public String outerHtml() {
StringBuilder accum = new StringBuilder(128);
outerHtml(accum);
return accum.toString();
}
protected void outerHtml(StringBuilder accum) {
new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings()))
.traverse(this);
}
// if this node has no document (or parent), retrieve the default output
// settings
private Document.OutputSettings getOutputSettings() {
return ownerDocument() != null ? ownerDocument().outputSettings()
: (new Document("")).outputSettings();
}
/**
* Get the outer HTML of this node.
*
* @param accum
* accumulator to place HTML into
*/
abstract void outerHtmlHead(StringBuilder accum, int depth,
Document.OutputSettings out);
abstract void outerHtmlTail(StringBuilder accum, int depth,
Document.OutputSettings out);
@Override
public String toString() {
return outerHtml();
}
protected void indent(StringBuilder accum, int depth,
Document.OutputSettings out) {
accum.append("\n").append(
StringUtil.padding(depth * out.indentAmount()));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
// todo: have nodes hold a child index, compare against that and parent
// (not children)
return false;
}
@Override
public int hashCode() {
int result = parentNode != null ? parentNode.hashCode() : 0;
// not children, or will block stack as they go back up to parent)
result = 31 * result + (attributes != null ? attributes.hashCode() : 0);
return result;
}
/**
* Create a stand-alone, deep copy of this node, and all of its children.
* The cloned node will have no siblings or parent node. As a stand-alone
* object, any changes made to the clone or any of its children will not
* impact the original node.
* <p>
* The cloned node may be adopted into another Document or node structure
* using {@link Element#appendChild(Node)}.
*
* @return stand-alone cloned node
*/
@Override
public Node clone() {
return doClone(null); // splits for orphan
}
protected Node doClone(Node parent) {
Node clone;
try {
clone = (Node) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
clone.parentNode = parent; // can be null, to create an orphan split
clone.siblingIndex = parent == null ? 0 : siblingIndex;
clone.attributes = attributes != null ? attributes.clone() : null;
clone.baseUri = baseUri;
clone.childNodes = new ArrayList<Node>(childNodes.size());
for (Node child : childNodes) {
clone.childNodes.add(child.doClone(clone)); // clone() creates
// orphans, doClone()
// keeps parent
}
return clone;
}
private static class OuterHtmlVisitor implements NodeVisitor {
private StringBuilder accum;
private Document.OutputSettings out;
OuterHtmlVisitor(StringBuilder accum, Document.OutputSettings out) {
this.accum = accum;
this.out = out;
}
@Override
public void head(Node node, int depth) {
node.outerHtmlHead(accum, depth, out);
}
@Override
public void tail(Node node, int depth) {
if (!node.nodeName().equals("#text")) {
node.outerHtmlTail(accum, depth, out);
}
}
}
}
|