blob: acf5d126f6ed7dfedebf6bca98c77ec24badf863 [file] [log] [blame]
Stuart McCulloch26e7a5a2011-10-17 10:31:43 +00001package aQute.libg.sax.filters;
2
3import java.util.Collections;
4import java.util.LinkedList;
5import java.util.List;
6
7import org.xml.sax.Attributes;
8import org.xml.sax.SAXException;
9
10import aQute.libg.sax.ContentFilterImpl;
11import aQute.libg.sax.SAXElement;
12
13public class MergeContentFilter extends ContentFilterImpl {
14
15 private int elementDepth = 0;
16
17 private final List<SAXElement> rootElements = new LinkedList<SAXElement>();
18
19 @Override
20 public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
21 if (elementDepth++ == 0) {
22 if (rootElements.isEmpty())
23 super.startElement(uri, localName, qName, atts);
24 else if (!rootElements.get(0).getqName().equals(qName))
25 throw new SAXException(String.format("Documents have inconsistent root element names: first was %s, current is %s.", rootElements.get(0).getqName(), qName));
26 rootElements.add(new SAXElement(uri, localName, qName, atts));
27 } else {
28 super.startElement(uri, localName, qName, atts);
29 }
30 }
31
32 @Override
33 public void endElement(String uri, String localName, String qName) throws SAXException {
34 if (--elementDepth > 0) {
35 super.endElement(uri, localName, qName);
36 }
37 }
38
39 @Override
40 public void processingInstruction(String target, String data) throws SAXException {
41 if (rootElements.isEmpty())
42 super.processingInstruction(target, data);
43 }
44
45 public void closeRootAndDocument() throws SAXException {
46 if (!rootElements.isEmpty()) {
47 SAXElement root = rootElements.get(0);
48 super.endElement(root.getUri(), root.getLocalName(), root.getqName());
49 }
50 super.endDocument();
51 }
52
53 public List<SAXElement> getRootElements() {
54 return Collections.unmodifiableList(rootElements);
55 }
56
57}