Stuart McCulloch | 26e7a5a | 2011-10-17 10:31:43 +0000 | [diff] [blame] | 1 | package aQute.libg.sax.filters; |
| 2 | |
| 3 | import java.util.Collections; |
| 4 | import java.util.LinkedList; |
| 5 | import java.util.List; |
| 6 | |
| 7 | import org.xml.sax.Attributes; |
| 8 | import org.xml.sax.SAXException; |
| 9 | |
| 10 | import aQute.libg.sax.ContentFilterImpl; |
| 11 | import aQute.libg.sax.SAXElement; |
| 12 | |
| 13 | public 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 | } |