1 package com.android.hotspot2.osu; 2 3 import com.android.hotspot2.omadm.XMLNode; 4 5 import org.xml.sax.Attributes; 6 import org.xml.sax.InputSource; 7 import org.xml.sax.SAXException; 8 import org.xml.sax.helpers.DefaultHandler; 9 10 import java.io.BufferedReader; 11 import java.io.IOException; 12 import java.io.InputStream; 13 import java.io.InputStreamReader; 14 import java.nio.charset.StandardCharsets; 15 16 import javax.xml.parsers.ParserConfigurationException; 17 import javax.xml.parsers.SAXParser; 18 import javax.xml.parsers.SAXParserFactory; 19 20 public class XMLParser extends DefaultHandler { 21 private final SAXParser mParser; 22 private final InputSource mInputSource; 23 24 private XMLNode mRoot; 25 private XMLNode mCurrent; 26 XMLParser(InputStream in)27 public XMLParser(InputStream in) throws ParserConfigurationException, SAXException { 28 mParser = SAXParserFactory.newInstance().newSAXParser(); 29 mInputSource = new InputSource(new BufferedReader( 30 new InputStreamReader(in, StandardCharsets.UTF_8))); 31 } 32 getRoot()33 public XMLNode getRoot() throws SAXException, IOException { 34 mParser.parse(mInputSource, this); 35 return mRoot; 36 } 37 38 @Override startElement(String uri, String localName, String qName, Attributes attributes)39 public void startElement(String uri, String localName, String qName, Attributes attributes) 40 throws SAXException { 41 XMLNode parent = mCurrent; 42 43 mCurrent = new XMLNode(mCurrent, qName, attributes); 44 //System.out.println("Added " + mCurrent.getTag() + ", atts " + mCurrent.getAttributes()); 45 46 if (mRoot == null) 47 mRoot = mCurrent; 48 else 49 parent.addChild(mCurrent); 50 } 51 52 @Override endElement(String uri, String localName, String qName)53 public void endElement(String uri, String localName, String qName) throws SAXException { 54 if (!qName.equals(mCurrent.getTag())) 55 throw new SAXException("End tag '" + qName + "' doesn't match current node: " + 56 mCurrent); 57 58 try { 59 mCurrent.close(); 60 } catch (IOException ioe) { 61 throw new SAXException("Failed to close element", ioe); 62 } 63 64 mCurrent = mCurrent.getParent(); 65 } 66 67 @Override characters(char[] ch, int start, int length)68 public void characters(char[] ch, int start, int length) throws SAXException { 69 mCurrent.addText(ch, start, length); 70 } 71 } 72