java/alt2xml-bin/src/cz/frantovo/alt2xml/výstup/EchoContentHandler.java
author František Kučera <franta-hg@frantovo.cz>
Thu, 05 Jun 2014 10:07:34 +0200
changeset 7 9107f7df660c
parent 3 java/alt2xml/src/cz/frantovo/alt2xml/výstup/EchoContentHandler.java@6c608fd8c019
child 11 aaf6648af0aa
permissions -rw-r--r--
přejmenování alt2xml → alt2xml-bin
     1 package cz.frantovo.alt2xml.výstup;
     2 
     3 import javax.xml.stream.XMLStreamException;
     4 import javax.xml.stream.XMLStreamWriter;
     5 import org.xml.sax.Attributes;
     6 import org.xml.sax.SAXException;
     7 import org.xml.sax.helpers.DefaultHandler;
     8 
     9 /**
    10  * Slouží k převodu právě parsovaného XML zpět na XML.
    11  * Určen pro testování a ladění a pro použití s neobvyklými „XML“ parsery,
    12  * které nečtou XML ale jiný jazyk (např. JSON, INI atd.), ale používají stejné rozhraní (SAX).
    13  * 
    14  * TODO: další typy uzlů a jmenné prostory.
    15  * @author fiki
    16  */
    17 public class EchoContentHandler extends DefaultHandler {
    18 
    19 	private XMLStreamWriter w;
    20 
    21 	/**
    22 	 * @param writer kam se bude vypisovat XML.
    23 	 */
    24 	public EchoContentHandler(XMLStreamWriter writer) {
    25 		w = writer;
    26 	}
    27 
    28 	@Override
    29 	public void startDocument() throws SAXException {
    30 		try {
    31 			w.writeStartDocument();
    32 		} catch (XMLStreamException e) {
    33 			throw new SAXException(e);
    34 		}
    35 	}
    36 
    37 	@Override
    38 	public void endDocument() throws SAXException {
    39 		try {
    40 			w.writeEndDocument();
    41 			w.close();
    42 		} catch (XMLStreamException e) {
    43 			throw new SAXException(e);
    44 		}
    45 	}
    46 
    47 	@Override
    48 	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
    49 		try {
    50 			w.writeStartElement(qName);
    51 
    52 			if (attributes != null) {
    53 				for (int i = 0; i < attributes.getLength(); i++) {
    54 					w.writeAttribute(attributes.getQName(i), attributes.getValue(i));
    55 				}
    56 			}
    57 
    58 			w.flush();
    59 		} catch (XMLStreamException e) {
    60 			throw new SAXException(e);
    61 		}
    62 	}
    63 
    64 	@Override
    65 	public void endElement(String uri, String localName, String qName) throws SAXException {
    66 		try {
    67 			w.writeEndElement();
    68 			w.flush();
    69 		} catch (XMLStreamException e) {
    70 			throw new SAXException(e);
    71 		}
    72 	}
    73 
    74 	@Override
    75 	public void characters(char[] ch, int start, int length) throws SAXException {
    76 		try {
    77 			w.writeCharacters(ch, start, length);
    78 			w.flush();
    79 		} catch (XMLStreamException e) {
    80 			throw new SAXException(e);
    81 		}
    82 	}
    83 }