1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.tika.sax.xpath;
18
19 import java.util.LinkedList;
20
21 import org.apache.tika.sax.ContentHandlerDecorator;
22 import org.xml.sax.Attributes;
23 import org.xml.sax.ContentHandler;
24 import org.xml.sax.SAXException;
25 import org.xml.sax.helpers.AttributesImpl;
26
27
28
29
30
31 public class MatchingContentHandler extends ContentHandlerDecorator {
32
33 private final LinkedList<Matcher> matchers = new LinkedList<Matcher>();
34
35 private Matcher matcher;
36
37 public MatchingContentHandler(ContentHandler delegate, Matcher matcher) {
38 super(delegate);
39 this.matcher = matcher;
40 }
41
42 public void startElement(
43 String uri, String localName, String name, Attributes attributes)
44 throws SAXException {
45 matchers.addFirst(matcher);
46 matcher = matcher.descend(uri, localName);
47
48 AttributesImpl matches = new AttributesImpl();
49 for (int i = 0; i < attributes.getLength(); i++) {
50 String attributeURI = attributes.getURI(i);
51 String attributeName = attributes.getLocalName(i);
52 if (matcher.matchesAttribute(attributeURI, attributeName)) {
53 matches.addAttribute(
54 attributeURI, attributeName, attributes.getQName(i),
55 attributes.getType(i), attributes.getValue(i));
56 }
57 }
58
59 if (matcher.matchesElement() || matches.getLength() > 0) {
60 super.startElement(uri, localName, name, matches);
61 if (!matcher.matchesElement()) {
62
63
64 matcher =
65 new CompositeMatcher(matcher, ElementMatcher.INSTANCE);
66 }
67 }
68 }
69
70 public void endElement(String uri, String localName, String name)
71 throws SAXException {
72 if (matcher.matchesElement()) {
73 super.endElement(uri, localName, name);
74 }
75 matcher = matchers.removeFirst();
76 }
77
78 public void characters(char[] ch, int start, int length)
79 throws SAXException {
80 if (matcher.matchesText()) {
81 super.characters(ch, start, length);
82 }
83 }
84
85 public void ignorableWhitespace(char[] ch, int start, int length)
86 throws SAXException {
87 if (matcher.matchesText()) {
88 super.ignorableWhitespace(ch, start, length);
89 }
90 }
91
92 public void processingInstruction(String target, String data) {
93
94 }
95
96 public void skippedEntity(String name) throws SAXException {
97
98 if (matcher.matchesText()) {
99 super.skippedEntity(name);
100 }
101 }
102
103 }