Android学习笔记_XML文件的解析
XML文件的解析:
方式:
1.DOM
2.SAX
例子:
public class XMLActivity extends Activity{
private Button parseButton;
public void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
parseButton =(Button)findViewById(R.id.parseButton);
parseButton.setOnClickListener(new ParseButtonListener());
}
class ParseButtonListener implements OnClickListener{
public void onClick(View v){
HttpDownloader hd=new HttpDownloader();
String resultStr=hd.download("http://192.168.0.1:8081/test/test.xml");
System.out.println(resultStr);
try{
SAXParserFactory factory=SAXParserFactory.newInstance();
XMLReader reader=factory.newSAXParser().getXMLReader();
reader.setContentHandler(new MyContentHandler());
reader.parse(new InputSource(new StringReader(resultStr)));
}catch(Exception e){
e.printStackTrace();
}
}
}
}
public calss MyContentHandler extends DefaultHandler{
String hisname,address,money,sex,status,tagName;
public void startDocument()throws SAXException{
System.out.println("===startDocument===");
}
public void endDocument()throws SAXException{
System.out.println("===endDocument===");
}
public void startElement(String namespaceURI,String localName,String qName,Attributes attr)throws SAXException{
if(localName.equals("worker")){
for(int i=0;i<attr.getLength();i++){
System.out.ptinln(attr.getLocalName(i)+"="+attr.getValue(i));
}
}
}
public void endElement(String namespaceURI,String localName,String qName,Attributes attr)throws SAXException{
System.out.println();
}
public void characters(char[] ch, int start, int length)throwsSAXException{
if(tagName.equals("name")){
hisname=new String(ch,start,length);
}else if(tagName.equals("sex")){
sex=new String(ch,start,length);
}else if(tagName.equals("address")){
address=new String(ch,start,length);
}else if(tagName.equals("status")){
status=new String(ch,start,length);
}else if(tagName.equals("money")){
money=new String(ch,start,length);
}
}
}