1 37 package org.webharvest.definition; 38 39 import java.io.IOException ; 40 import java.io.InputStream ; 41 42 import javax.xml.parsers.*; 43 44 import org.apache.log4j.Logger; 45 import org.webharvest.utils.Stack; 46 import org.xml.sax.Attributes ; 47 import org.xml.sax.SAXException ; 48 import org.xml.sax.helpers.DefaultHandler ; 49 50 51 public class XmlParser extends DefaultHandler { 52 53 protected static Logger log = Logger.getLogger(XmlParser.class); 54 55 XmlNode root; 56 57 private transient Stack elementStack = new Stack(); 59 60 public static XmlNode parse(InputStream in) { 61 long startTime = System.currentTimeMillis(); 62 63 XmlParser handler = new XmlParser(); 64 try { 65 SAXParserFactory parserFactory = SAXParserFactory.newInstance(); 66 parserFactory.setValidating(false); 67 parserFactory.setNamespaceAware(false); 68 69 SAXParser parser = parserFactory.newSAXParser(); 70 71 parser.parse(in, handler); 73 74 log.info("XML parsed in " + (System.currentTimeMillis() - startTime) + "ms."); 75 } catch (SAXException e) { 76 e.printStackTrace(); 78 } catch (IOException e) { 79 e.printStackTrace(); 81 } catch (ParserConfigurationException e) { 82 e.printStackTrace(); 84 } 85 86 return handler.root; 87 } 88 89 private XmlNode getCurrentNode() { 90 return elementStack.size() > 0 ? (XmlNode) elementStack.peek() : null; 91 } 92 93 public void characters(char[] ch, int start, int length) throws SAXException { 94 XmlNode currNode = getCurrentNode(); 95 if (currNode != null) { 96 String value = new String (ch, start, length).trim(); 97 String text = currNode.getText(); 98 if (text == null) { 99 text = value; 100 } else { 101 text += " " + value; 102 } 103 currNode.setText(text); 104 if (!"".equals(value)) { 105 currNode.addElement(value); 106 } 107 } 108 } 109 110 public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { 111 XmlNode currNode = getCurrentNode(); 112 XmlNode newNode = new XmlNode(qName, currNode); 113 elementStack.push(newNode); 114 115 if (currNode == null) { 116 root = newNode; 117 } 118 119 int attsCount = attributes.getLength(); 120 for (int i = 0; i < attsCount; i++) { 121 newNode.addAttribute( attributes.getQName(i), attributes.getValue(i) ); 122 } 123 } 124 125 public void endElement(String uri, String localName, String qName) throws SAXException { 126 if (elementStack.size() > 0) { 127 elementStack.pop(); 128 } 129 } 130 131 } | Popular Tags |