android webservices sax 传输并解析xml
16lz
2021-12-04
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;@Overridepublic 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);}}}@Overridepublic void endDocument() throws SAXException {super.endDocument();}@Overridepublic 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 = "";}@Overridepublic void startDocument() throws SAXException {super.startDocument();list = new ArrayList<QuestionItem>();}@Overridepublic 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文件的界面
更多相关文章
- Android(安卓)Studio 4.0 新功能之 AndroidKotlin Live Template
- Android根据联系人姓名首字符顺序读取通讯录
- SSH服务器与Android通信(2)--Android客户端接收数据
- Android(安卓)TextView的字符过滤功能
- Hello Android
- [置顶] 浅谈Android的资源编译过程
- SSH服务器与Android通信(2)--Android客户端接收数据
- Android中WebView加载本地Html,与JavaScript与Android方法相互传
- Android中WebView加载本地Html,与JavaScript与Android方法相互传