android通过服务器后台webservices返回xml数据(问卷),保存本地,并通过sax解析xml
【1】android通过webservice接收xml字符
//调用webservices获取xml问卷
SoapObject QuestionRe =(SoapObject) RemoteWebservice.CallNewQuestion("116307");
if (!QuestionRe.getProperty("wbsGetQuestionInfoResult").toString().equals("error"))
{
//下载最新问卷
if (XMLUtil.writeToXml(Login.this, QuestionRe.getProperty("wbsGetQuestionInfoResult").toString())== true)
{
//Toast.makeText(Login.this,"已经下载最新问卷",Toast.LENGTH_LONG).show();
}
}
【2】把xml字符接收并保存到本地文件
/**
* 字符串文本保存为本地XML
* @param str xml字符串
* @return
* @author fubin.pan
*/
public static boolean writeToXml(Context context,String str)
{
String fileName = "admin_question.xml";
try {
OutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
try{
OutputStreamWriter osw=new OutputStreamWriter(fos);
osw.write(str);
osw.close();
fos.close();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}catch (FileNotFoundException e) {
e.printStackTrace();
return false;
}
}
【3】通过sax解析本地xml文件
FileInputStream inStream=questionitemlist2.this.openFileInput("admin_question.xml");
Xml.parse(new InputStreamReader(inStream), quesHandler);
public class QuestionHandler extends DefaultHandler {
private List<QuestionItem> list;
private QuestionItem item;
private String tag = "";
private StringBuffer buffer;
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);
if(item!=null){
String data = new String(ch,start,length);
if(tag.equals("code")){
item.setCode(data);
}else if(tag.equals("name")){
item.setName(data);
}else if(tag.equals("displayName")){
item.setDisplayName(data);
}else if(tag.equals("pubDate")){
item.setitemType(data);
}else if(tag.equals("toEnd")){
item.setToEnd(data);
}else if(tag.equals("toNext")){
item.setToNext(data);
}
}
}
@Override
public void endDocument() throws SAXException {
super.endDocument();
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);
if(localName.equals("item")){
list.add(item);
item = null;
buffer = null;
}
tag = "";
}
@Override
public void startDocument() throws SAXException {
super.startDocument();
list = new ArrayList<QuestionItem>();
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);
if(localName.equals("item")){
item = new QuestionItem();
buffer = new StringBuffer();
}
tag = localName;
}
public List<QuestionItem> getData(){
return list;
}
}
【4】展现xml文件的界面