I just went straight to the code.
Try {string systemid = "<? XML version = \ "1.0 \" encoding = \ "UTF-8 \"?> <Student> <Name> Zhang translated into </Name> <age> 22 </age> <address> Hubei Province </address> </student> "; saxparserfactory factory = saxparserfactory. newinstance (); saxparser parser = factory. newsaxparser (); xmlreader reader = parser. getxmlreader (); reader. setcontenthandler (New myhandler (this); byte [] BB = systemid. getbytes (); bytearrayinputstream BAIS = new bytearrayinputstream (bb); inputsource in = new inputsource (BAIS); reader. parse (in);} catch (exception e) {e. printstacktrace ();}
The code in myhanlder is
package com.zhycheng;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;import android.app.Activity;import android.widget.Toast;public class MyHandler extends DefaultHandler{String tagname=null;Activity s=null;public MyHandler(Activity d){this.s=d;}@Overridepublic void characters(char[] ch, int start, int length)throws SAXException {// TODO Auto-generated method stubif("age".equals(tagname)){String s=new String(ch,start,length);Toast.makeText(this.s, s, Toast.LENGTH_SHORT).show();}super.characters(ch, start, length);}@Overridepublic void endDocument() throws SAXException {// TODO Auto-generated method stubsuper.endDocument();tagname=null;Toast.makeText(s, "endDocument", Toast.LENGTH_SHORT).show();System.out.println("endDocument");}@Overridepublic void endElement(String uri, String localName, String qName)throws SAXException {// TODO Auto-generated method stubsuper.endElement(uri, localName, qName);}@Overridepublic void startDocument() throws SAXException {// TODO Auto-generated method stubsuper.startDocument();Toast.makeText(s, "startDocument", Toast.LENGTH_SHORT).show();System.out.println("startDocument");}@Overridepublic void startElement(String uri, String localName, String qName,Attributes attributes) throws SAXException {// TODO Auto-generated method stubsuper.startElement(uri, localName, qName, attributes);tagname=localName;Toast.makeText(s, tagname, Toast.LENGTH_SHORT).show();System.out.println(tagname);}}
This can be parsed.
In addition, if you want to parse the tag attributes, you can use the following code:
for (int i = 0; i < attr.getLength(); i++){System.out.println(attr.getLocalName(i) + "=" + attr.getValue(i));}