1package com.android.server.wifi.hotspot2.omadm; 2 3import org.xml.sax.Attributes; 4import org.xml.sax.InputSource; 5import org.xml.sax.SAXException; 6import org.xml.sax.helpers.DefaultHandler; 7 8import java.io.IOException; 9import java.io.StringReader; 10 11import javax.xml.parsers.ParserConfigurationException; 12import javax.xml.parsers.SAXParser; 13import javax.xml.parsers.SAXParserFactory; 14 15/** 16 * Parses an OMA-DM XML tree. 17 * OMA-DM = Open Mobile Association Device Management 18 */ 19public class OMAParser extends DefaultHandler { 20 private XMLNode mRoot; 21 private XMLNode mCurrent; 22 23 public OMAParser() { 24 mRoot = null; 25 mCurrent = null; 26 } 27 28 public MOTree parse(String text, String urn) throws IOException, SAXException { 29 try { 30 SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); 31 parser.parse(new InputSource(new StringReader(text)), this); 32 return new MOTree(mRoot, urn); 33 } catch (ParserConfigurationException pce) { 34 throw new SAXException(pce); 35 } 36 } 37 38 public XMLNode getRoot() { 39 return mRoot; 40 } 41 42 @Override 43 public void startElement(String uri, String localName, String qName, Attributes attributes) 44 throws SAXException { 45 XMLNode parent = mCurrent; 46 47 mCurrent = new XMLNode(mCurrent, qName, attributes); 48 49 if (mRoot == null) 50 mRoot = mCurrent; 51 else 52 parent.addChild(mCurrent); 53 } 54 55 @Override 56 public void endElement(String uri, String localName, String qName) throws SAXException { 57 if (!qName.equals(mCurrent.getTag())) 58 throw new SAXException("End tag '" + qName + "' doesn't match current node: " + 59 mCurrent); 60 61 try { 62 mCurrent.close(); 63 } catch (IOException ioe) { 64 throw new SAXException("Failed to close element", ioe); 65 } 66 67 mCurrent = mCurrent.getParent(); 68 } 69 70 @Override 71 public void characters(char[] ch, int start, int length) throws SAXException { 72 mCurrent.addText(ch, start, length); 73 } 74} 75