SAXParser 를 이용하여 String을 읽어서 Document 완성하기

static class SampleHandler extends DefaultHandler { public void startDocument() { System.out.println(“startDocument”); } public void endDocument() { System.out.println(“endDocument”); } public void startElement(String namespaceURI, String localName, String qName, Attributes attrs) { System.out.println(“startElement: ” + qName + ” with “+attrs.getLength()+” attribute(s).”); } public void endElement(String namespaceURI, String localName, String qName) { System.out.println(“endElement: ” + qName); } public void characters(char[] ch, int start, int length) { System.out.print(“characters: “); for (int i = 0; i < length; i++) { System.out.print(ch[start + i]); } System.out.println(); } } public static void main(String[] args) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); DefaultHandler dh = new SampleHandler(); parser.parse(new ByteArrayInputStream(“<root><person id=\”test1234\”><name>이름</name></person></root>”.getBytes()), dh); } 이렇게 실행하면 SampleHandler에 정의한 메소드에 태그의 개시 및 종료시에 이벤트를 발생시켜줍니다. 결과는 아래와 같습니다.

startDocument startElement: root with 0 attribute(s). startElement: person with 1 attribute(s). startElement: name with 0 attribute(s). characters: 이름 endElement: name endElement: person endElement: root endDocument

실제 구현 예제

class PushDocumentHandler implements ContentHandler {
	private static final Log logger = LogFactory
			.getLog(PushDocumentHandler.class);
	private Document doc;
	private Stack<Element> elems;
	public PushDocumentHandler() {
		try {
			DocumentBuilder db = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			doc = db.newDocument();
			elems = new Stack<Element>();
		} catch (ParserConfigurationException e) {
			logger.error(e.getMessage(), e);
		}
	}
	@Override
	public void characters(char[] data, int off, int count) throws SAXException {
		Element cur = elems.peek();
		cur.setTextContent(new String(data, off, count));
	}
	@Override
	public void endDocument() throws SAXException {
	}
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		elems.pop();
	}
	@Override
	public void startElement(String uri, String localName, String qName, Attributes arg1)
			throws SAXException {
		Element newE = doc.createElement(qName);
		Element parent = null;
		if (!elems.isEmpty()) {
			parent = elems.peek();
		}
		if (parent != null) {
			parent.appendChild(newE);
		} else {
			doc.appendChild(newE);
		}
		elems.add(newE);
		for (int i = 0; i < arg1.getLength(); i++) {
			String att = arg1.getQName(i);
			String val = arg1.getValue(i);
			newE.setAttribute(att, val);
		}
	}
	public Document getDocument() {
		return doc;
	}
	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
		// TODO Auto-generated method stub
	}
	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
		// TODO Auto-generated method stub
	}
	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {
		// TODO Auto-generated method stub
	}
	@Override
	public void setDocumentLocator(Locator locator) {
		// TODO Auto-generated method stub
	}
	@Override
	public void skippedEntity(String name) throws SAXException {
		// TODO Auto-generated method stub
	}
	@Override
	public void startDocument() throws SAXException {
		// TODO Auto-generated method stub
	}
	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
		// TODO Auto-generated method stub
	}
}

참고사이트 http://www.atmarkit.co.jp/fxml/rensai/xmljava04/xmljava02.html]]>

Related Posts