1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.any23.validator;
19
20 import org.apache.any23.extractor.html.DomUtils;
21 import org.w3c.dom.Attr;
22 import org.w3c.dom.Document;
23 import org.w3c.dom.NamedNodeMap;
24 import org.w3c.dom.Node;
25
26 import java.net.URI;
27 import java.util.List;
28 import java.util.Locale;
29
30
31
32
33
34
35
36 public class DefaultDOMDocument implements DOMDocument {
37
38 private URI documentIRI;
39
40 private Document document;
41
42 public DefaultDOMDocument(URI documentIRI, Document document) {
43 if (documentIRI == null) {
44 throw new NullPointerException("documentIRI cannot be null.");
45 }
46 if (document == null) {
47 throw new NullPointerException("document cannot be null.");
48 }
49 this.documentIRI = documentIRI;
50 this.document = document;
51 }
52
53 public URI getDocumentIRI() {
54 return documentIRI;
55 }
56
57 public Document getOriginalDocument() {
58 return document;
59 }
60
61 public List<Node> getNodes(String xPath) {
62 return DomUtils.findAll(document, xPath);
63 }
64
65 public Node getNode(String xPath) {
66 List<Node> nodes = DomUtils.findAll(document, xPath);
67 if (nodes.size() == 0) {
68 throw new IllegalArgumentException(String.format(Locale.ROOT, "Cannot find node at XPath '%s'", xPath));
69 }
70 if (nodes.size() > 1) {
71 throw new IllegalArgumentException(
72 String.format(Locale.ROOT, "The given XPath '%s' corresponds to more than one node.", xPath));
73 }
74 return nodes.get(0);
75 }
76
77 public void addAttribute(String xPath, String attrName, String attrValue) {
78 Node node = getNode(xPath);
79 NamedNodeMap namedNodeMap = node.getAttributes();
80 Attr attr = document.createAttribute(attrName);
81 attr.setNodeValue(attrValue);
82 namedNodeMap.setNamedItem(attr);
83 }
84
85 public List<Node> getNodesWithAttribute(String attrName) {
86 return DomUtils.findAllByAttributeName(document, attrName);
87 }
88
89 }