class SaxParseHandler extends DefaultHandler { String result; public String parseToString() { return result; } String str = null; /** * xml开始时,执行此函数 */ @Override public void startDocument() throws SAXException { // Log.e("TEST", "startDocument"); } /** * xml结束时,执行此函数 */ @Override public void endDocument() throws SAXException { // Log.e("TEST", "endDocument"); } /** * xml标签开始时,执行此函数,读取标签名称,和标签内的属性 */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("group".equals(localName)) { String groupName = attributes.getValue(0); String num = attributes.getValue(1); resultresult = result + "groupName=" + groupName + " num =" + num + "\n"; } else if ("person".equals(localName)) { String personName = attributes.getValue(0); String age = attributes.getValue(1); // 和getValue(1)等效 // String txt = attributes.getValue("age"); resultresult = result + "personName" + personName + " age=" + age + "\n"; } else { str = localName; } // Log.e("TEST", "startElement"); } /** * xml标签结束时,执行此函数 */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { str = null; // Log.e("TEST", "endElement"); } /** * 解析标签内的值,如<chinese>ssss</chinese>,为了读取"ssss" */ @Override public void characters(char[] ch, int start, int length) throws SAXException { if (str != null) { String data = new String(ch, start, length); //xml文件格式化的时候容易产生以下换行,制表符等特殊字符, //这些需要特别注意处理 Pattern p = Pattern.compile("\\s*|\t|\r|\n"); Matcher m = p.matcher(data); data = m.replaceAll(""); if ("chinese".equals(str)) { if(!data.equals("")){ String chinese = data; resultresult = result + "chinese=" + chinese; } } else if ("english".equals(str)) { if(!data.equals("")){ String english = data; resultresult = result + "english=" + english + "\n"; } } } } }
Android SAX解析 XML方式(2)
内容版权声明:除非注明,否则皆为本站原创文章。