SAX를 이용한 Java XML 샘플 코드 DarkKaiser, 2010년 5월 12일2023년 9월 6일 import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; import javax.xml.parsers.*; public class SaxSample { public static void main(String[] args) { // SAX를 준비한다. SAXParser saxParser = null; try { SAXParserFactory saxFactory = SAXParserFactory.newInstance(); saxParser = saxFactory.newSAXParser(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } // 핸들러를 작성한다. SaxCustomHandler saxHandler = new SaxCustomHandler(); try { saxParser.parse(new FileInputStream("f:\\1.xml"), saxHandler); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } // SAX 핸들러 클래스 class SaxCustomHandler extends DefaultHandler { @Override public void startDocument() { System.out.println("XML 문서가 시작 되었습니다."); } @Override public void endDocument() { System.out.println("XML 문서가 종료 되었습니다."); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { String elementName = localName; if ("".equals(elementName) == true) elementName = qName; System.out.print("<" + elementName); if (attributes != null) { for (int i = 0; i < attributes.getLength(); ++i) { String attributeName = attributes.getLocalName(i); if ("".equals(attributeName) == true) attributeName = attributes.getQName(i); System.out.print(" " + attributeName + "=\"" + attributes.getValue(i) + "\""); } } System.out.print(">"); } @Override public void endElement(String uri, String localName, String qName) throws SAXException { String elementName = localName; if ("".equals(elementName) == true) elementName = qName; System.out.print("</" + elementName + ">"); } @Override public void characters(char[] ch, int start, int length) throws SAXException { System.out.print(new String(ch, start, length)); } } Java SAXXML