您好,登錄后才能下訂單哦!
小編給大家分享一下android中sax解析xml文件的示例,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
使用RootElement這個類來解析的,RootElement 內置了defaultHandler的子類,
RootElement 源碼如下:
public class RootElement extends Element { final Handler handler = new Handler(); /** * Constructs a new root element with the given name. * * @param uri the namespace * @param localName the local name */ public RootElement(String uri, String localName) { super(null, uri, localName, 0); } /** * Constructs a new root element with the given name. Uses an empty string * as the namespace. * * @param localName the local name */ public RootElement(String localName) { this("", localName); } /** * Gets the SAX {@code ContentHandler}. Pass this to your SAX parser. */ public ContentHandler getContentHandler() { return this.handler; } class Handler extends DefaultHandler { Locator locator; int depth = -1; Element current = null; StringBuilder bodyBuilder = null; @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { int depth = ++this.depth; if (depth == 0) { // This is the root element. startRoot(uri, localName, attributes); return; } // Prohibit mixed text and elements. if (bodyBuilder != null) { throw new BadXmlException("Encountered mixed content" + " within text element named " + current + ".", locator); } // If we're one level below the current element. if (depth == current.depth + 1) { // Look for a child to push onto the stack. Children children = current.children; if (children != null) { Element child = children.get(uri, localName); if (child != null) { start(child, attributes); } } } } void startRoot(String uri, String localName, Attributes attributes) throws SAXException { Element root = RootElement.this; if (root.uri.compareTo(uri) != 0 || root.localName.compareTo(localName) != 0) { throw new BadXmlException("Root element name does" + " not match. Expected: " + root + ", Got: " + Element.toString(uri, localName), locator); } start(root, attributes); } void start(Element e, Attributes attributes) { // Push element onto the stack. this.current = e; if (e.startElementListener != null) { e.startElementListener.start(attributes); } if (e.endTextElementListener != null) { this.bodyBuilder = new StringBuilder(); } e.resetRequiredChildren(); e.visited = true; } @Override public void characters(char[] buffer, int start, int length) throws SAXException { if (bodyBuilder != null) { bodyBuilder.append(buffer, start, length); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { Element current = this.current; // If we've ended the current element... if (depth == current.depth) { current.checkRequiredChildren(locator); // Invoke end element listener. if (current.endElementListener != null) { current.endElementListener.end(); } // Invoke end text element listener. if (bodyBuilder != null) { String body = bodyBuilder.toString(); bodyBuilder = null; // We can assume that this listener is present. current.endTextElementListener.end(body); } // Pop element off the stack. this.current = current.parent; } depth--; } } }
以上是RootElement類得源碼,從源碼可以看出,它只是將defaultHandler簡單的處理一下。
具體應用可以參照我寫的測試源碼
/** * sax解析xml的第二種方式 * 用XMLReader 也是sax的一種方式 * @return */ private String saxParseSecond(){ //讀取src下xml文件 InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("saxTest.xml"); SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parse = factory.newSAXParser(); XMLReader reader = parse.getXMLReader(); reader.setContentHandler(getRootElement().getContentHandler()); reader.parse(new InputSource(inputStream)); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
/** * * @return 返回設置好處理機制的rootElement */ private RootElement getRootElement(){ /*rootElement代表著根節點,參數為根節點的tagName*/ RootElement rootElement = new RootElement("classes"); /*獲取一類子節點,并為其設置相應的事件 * 這里需要注意,雖然我們只設置了一次group的事件,但是我們文檔中根節點下的所有 * group卻都可以觸發這個事件。 * */ Element groupElement = rootElement.getChild("group"); // 讀到元素開始位置時觸發,如讀到<group>時 groupElement.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { // Log.i("TEST", "start"); String groupName = attributes.getValue("name"); String groupNum = attributes.getValue("num"); result = result+"groupName ="+groupName+"groupNum = "+groupNum+"\n"; } }); //讀到元素結束位置時觸發,如讀到</group>時 groupElement.setEndElementListener(new EndElementListener() { @Override public void end() { } }); Element personElement = groupElement.getChild("person"); //讀取<person>標簽觸發 personElement.setStartElementListener(new StartElementListener() { @Override public void start(Attributes attributes) { String personName = attributes.getValue("name"); String age = attributes.getValue("age"); result = result+"personName ="+personName+"age = "+age+"\n"; } }); //讀取</person>標簽觸發 personElement.setEndElementListener(new EndElementListener() { @Override public void end() { } }); Element chinese = personElement.getChild("chinese"); // chinese.setTextElementListener(new TextElementListener() { // // @Override // public void end(String body) { // // TODO Auto-generated method stub // // } // // @Override // public void start(Attributes attributes) { // // TODO Auto-generated method stub // // } // }); // 讀到文本的末尾時觸發,這里的body即為文本的內容部分 chinese.setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(body); body = m.replaceAll(""); result = result+"chinese ="+body; } }); Element english = personElement.getChild("english"); english.setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(body); body = m.replaceAll(""); result = result+"english ="+body+"\n"; } }); return rootElement; }
我們都知道通過SAXParser對象解析xml的方式,這里我們又從代碼中看到了利用另一個對象XMLReader進行解析,那么兩者到底有什么聯系和區別呢?
其實SAXParser是在SAX 1.0 定義的,而XMLReader則是在2.0中才開始出現的。你可以認為XMLReader的出現是為了替代SAXParser解析的,兩者本質上干的事情是一樣的,只不過XMLReader的功能更加的強悍而已。
關于XMLReader的獲取方式,除了通過SAXParser的getXMLReader方法獲得之外,我們還可以通過以下兩種方式。
XMLReader parser=XMLReaderFactory.createXMLReader(); (1) XMLReader parser=XMLReaderFactory.createXMLReader(String className); (2)
看完了這篇文章,相信你對“android中sax解析xml文件的示例”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。