当是练习吧,分别以JSON、SAX、DOM、XML(android.util.XML)来解析字符串。

个人感觉这四种方式的实现由难到易的顺序是:SAX→XML→DOM→JSON。

JSON解析的内容如下,文件名为devdiv.json,存于工程的assets目录下:

[xhtml] view plain copy
  1. {
  2. "code":"1",
  3. "result":{
  4. "title":"Devdiv移动开发社区",
  5. "title_url":"http://www.devdiv.com/forum.php",
  6. "development_forum_name":"开发讨论区",
  7. "development_forum":[
  8. {"name":"WindowsPhone论坛","url":"http://www.devdiv.com/forum-windows-phone-mobile-1.html"},
  9. {"name":"Android论坛","url":"http://www.devdiv.com/forum-android-1.html"},
  10. {"name":"iOS/iPhone论坛","url":"http://www.devdiv.com/forum-iphone-1.html"}
  11. ]
  12. }
  13. }

剩下三个解析内容如下,文件名为devdiv.xml,存于工程的assets目录下:

[xhtml] view plain copy
  1. <root>
  2. <title>Devdiv移动开发社区</title>
  3. <body>开发讨论区</body>
  4. <itemurl="http://www.devdiv.com/forum-windows-phone-mobile-1.html">WindowsPhone论坛</item>
  5. <itemurl="http://www.devdiv.com/forum-android-1.html">Android论坛</item>
  6. <itemurl="http://www.devdiv.com/forum-iphone-1.html">iOS/iPhone论坛</item>
  7. </root>

本例子解析后显示效果:

对于DOM的解析,在SDK8及以上版本有两种方法。代码如下:

[java] view plain copy
  1. packagelab.sodino.string;
  2. importjava.io.IOException;
  3. importjava.io.InputStream;
  4. importjava.util.Vector;
  5. importjavax.xml.parsers.DocumentBuilder;
  6. importjavax.xml.parsers.DocumentBuilderFactory;
  7. importjavax.xml.parsers.FactoryConfigurationError;
  8. importjavax.xml.parsers.ParserConfigurationException;
  9. importjavax.xml.parsers.SAXParser;
  10. importjavax.xml.parsers.SAXParserFactory;
  11. importorg.json.JSONArray;
  12. importorg.json.JSONException;
  13. importorg.json.JSONObject;
  14. importorg.w3c.dom.Document;
  15. importorg.w3c.dom.Element;
  16. importorg.w3c.dom.Node;
  17. importorg.w3c.dom.NodeList;
  18. importorg.xml.sax.Attributes;
  19. importorg.xml.sax.SAXException;
  20. importorg.xml.sax.helpers.DefaultHandler;
  21. importandroid.app.Activity;
  22. importandroid.graphics.Typeface;
  23. importandroid.os.Build;
  24. importandroid.os.Bundle;
  25. importandroid.text.SpannableString;
  26. importandroid.text.Spanned;
  27. importandroid.text.method.LinkMovementMethod;
  28. importandroid.text.style.StyleSpan;
  29. importandroid.text.style.URLSpan;
  30. importandroid.util.Log;
  31. importandroid.view.View;
  32. importandroid.widget.Button;
  33. importandroid.widget.TextView;
  34. publicclassTextActextendsActivity{
  35. publicstaticfinalStringTAG="ANDROID_LAB";
  36. privateButtonbtnJSON;
  37. privateButtonbtnSAX;
  38. privateButtonbtnDOM;
  39. privateButtonbtnXML;
  40. privateBtnListenerbtnListener;
  41. privateTextViewtxtInfo;
  42. publicvoidonCreate(BundlesavedInstanceState){
  43. super.onCreate(savedInstanceState);
  44. setContentView(R.layout.main);
  45. btnListener=newBtnListener();
  46. btnDOM=(Button)findViewById(R.id.btnDOM);
  47. btnDOM.setOnClickListener(btnListener);
  48. txtInfo=(TextView)findViewById(R.id.txtInfo);
  49. }
  50. privatevoidinflateTextViewByBean(Beanbean){
  51. intspanCount=4;
  52. int[]start=newint[spanCount];
  53. int[]end=newint[spanCount];
  54. StringBufferbuffer=newStringBuffer();
  55. buffer.append(bean.type+"/n");
  56. buffer.append(bean.title+"/n");
  57. start[0]=buffer.length();
  58. buffer.append(bean.development_forum_name+"/n");
  59. end[0]=buffer.length();
  60. for(inti=0;i<bean.vecName.size();i++){
  61. start[i+1]=buffer.length();
  62. buffer.append(bean.vecName.get(i)+"/n");
  63. end[i+1]=buffer.length();
  64. }
  65. SpannableStringspannableString=newSpannableString(buffer.toString());
  66. spannableString.setSpan(newStyleSpan(Typeface.ITALIC),start[0],end[0],
  67. Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  68. for(inti=0;i<bean.vecName.size();i++){
  69. spannableString.setSpan(newURLSpan(bean.vecUrl.get(i)),start[i+1],end[i+1],
  70. Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
  71. }
  72. txtInfo.setText(spannableString);
  73. txtInfo.setMovementMethod(LinkMovementMethod.getInstance());
  74. }
  75. classBtnListenerimplementsButton.OnClickListener{
  76. publicvoidonClick(Viewview){
  77. if(view==btnJSON){
  78. showInfoFromJSON();
  79. }elseif(view==btnSAX){
  80. showInfoFromSAXParser();
  81. }elseif(view==btnDOM){
  82. showInfoFromDOM();
  83. }elseif(view==btnXML){
  84. showInfoFromXML();
  85. }
  86. }
  87. }
  88. publicvoidshowInfoFromJSON(){
  89. Beanbean=newBean();
  90. bean.type="InflatedbyJSON/n";
  91. Stringcontent="";
  92. InputStreamis=null;
  93. try{
  94. is=getAssets().open("devdiv.json");
  95. byte[]data=newbyte[is.available()];
  96. is.read(data);
  97. content=newString(data);
  98. Log.d(TAG,"content="+content);
  99. JSONObjectjsonContent=newJSONObject(content);
  100. intcode=jsonContent.getInt("code");
  101. //假设默认code为1时才是正确的json数据。
  102. if(code==1){
  103. JSONObjectjsonResult=jsonContent.getJSONObject("result");
  104. bean.title=jsonResult.getString("title");
  105. bean.development_forum_name=jsonResult.getString("development_forum_name");
  106. bean.vecName=newVector<String>();
  107. bean.vecUrl=newVector<String>();
  108. JSONArraydevArr=jsonResult.getJSONArray("development_forum");
  109. Stringtmp="";
  110. for(inti=0;i<devArr.length();i++){
  111. JSONObjectobj=devArr.getJSONObject(i);
  112. tmp=obj.getString("name");
  113. bean.vecName.add(tmp);
  114. tmp=obj.getString("url");
  115. bean.vecUrl.add(tmp);
  116. }
  117. inflateTextViewByBean(bean);
  118. }else{
  119. Log.d(TAG,"Aerroroccurwhenparseajsonfile.");
  120. }
  121. }catch(IOExceptione){
  122. e.printStackTrace();
  123. }catch(JSONExceptione){
  124. e.printStackTrace();
  125. }finally{
  126. try{
  127. if(is!=null){
  128. is.close();
  129. }
  130. }catch(IOExceptionie){
  131. ie.printStackTrace();
  132. }
  133. }
  134. }
  135. publicvoidshowInfoFromXML(){
  136. Beanbean=newBean();
  137. bean.type="InflatedbyXML/n";
  138. bean.vecName=newVector<String>();
  139. bean.vecUrl=newVector<String>();
  140. MyXMLHandlerxmlHandler=null;
  141. InputStreamis=null;
  142. xmlHandler=newMyXMLHandler(bean);
  143. try{
  144. is=getAssets().open("devdiv.xml");
  145. //一句话就OK了。
  146. android.util.Xml.parse(is,android.util.Xml.Encoding.UTF_8,xmlHandler);
  147. }catch(IOExceptione){
  148. e.printStackTrace();
  149. }catch(SAXExceptione){
  150. e.printStackTrace();
  151. }finally{
  152. try{
  153. if(is!=null){
  154. is.close();
  155. }
  156. }catch(IOExceptionie){
  157. ie.printStackTrace();
  158. }
  159. }
  160. inflateTextViewByBean(bean);
  161. }
  162. publicvoidshowInfoFromDOM(){
  163. Beanbean=newBean();
  164. bean.type="InflatedbyDOM/n";
  165. bean.vecName=newVector<String>();
  166. bean.vecUrl=newVector<String>();
  167. InputStreamis=null;
  168. DocumentBuilderFactorydomFactory=DocumentBuilderFactory.newInstance();
  169. try{
  170. is=getAssets().open("devdiv.xml");
  171. NodeListlist=null;
  172. DocumentBuilderdomBuilder=domFactory.newDocumentBuilder();
  173. Documentdoc=domBuilder.parse(is);
  174. //获取根目录
  175. ElementrootElement=doc.getDocumentElement();
  176. //输出[rootElement=root]
  177. Log.d(TAG,"rootElement="+rootElement.getNodeName());
  178. list=rootElement.getElementsByTagName("title");
  179. if(Integer.parseInt(Build.VERSION.SDK)>=8){
  180. //在已提前获只有一个title的情况下直接去取list.item(0)
  181. bean.title=list.item(0).getTextContent();
  182. //在已提前获只有一个body的情况下直接去取list.item(0)
  183. list=rootElement.getElementsByTagName("body");
  184. bean.development_forum_name=list.item(0).getTextContent();
  185. //多个item的读取情形
  186. list=rootElement.getElementsByTagName("item");
  187. for(inti=0;i<list.getLength();i++){
  188. Nodenode=list.item(i);
  189. bean.vecUrl.add(node.getAttributes().item(0).getTextContent());
  190. bean.vecName.add(node.getTextContent());
  191. }
  192. }else{
  193. //在已提前获只有一个title的情况下直接去取list.item(0)
  194. bean.title=list.item(0).getFirstChild().getNodeValue();
  195. //在已提前获只有一个body的情况下直接去取list.item(0)
  196. list=rootElement.getElementsByTagName("body");
  197. bean.development_forum_name=list.item(0).getFirstChild().getNodeValue();
  198. //多个item的读取情形
  199. list=rootElement.getElementsByTagName("item");
  200. for(inti=0;i<list.getLength();i++){
  201. Nodenode=list.item(i);
  202. bean.vecUrl.add(node.getAttributes().getNamedItem("url").getNodeValue());
  203. bean.vecName.add(node.getFirstChild().getNodeValue());
  204. }
  205. }
  206. }catch(ParserConfigurationExceptione){
  207. e.printStackTrace();
  208. }catch(IOExceptione){
  209. e.printStackTrace();
  210. }catch(SAXExceptione){
  211. e.printStackTrace();
  212. }finally{
  213. try{
  214. if(is!=null){
  215. is.close();
  216. }
  217. }catch(IOExceptionie){
  218. ie.printStackTrace();
  219. }
  220. }
  221. inflateTextViewByBean(bean);
  222. }
  223. publicvoidshowInfoFromSAXParser(){
  224. Beanbean=newBean();
  225. bean.vecName=newVector<String>();
  226. bean.vecUrl=newVector<String>();
  227. bean.type="InflatedbySAXParser/n";
  228. InputStreamis=null;
  229. SAXParserparser=null;
  230. MyXMLHandlerxmlHandler=null;
  231. try{
  232. parser=SAXParserFactory.newInstance().newSAXParser();
  233. xmlHandler=newMyXMLHandler(bean);
  234. is=getAssets().open("devdiv.xml");
  235. parser.parse(is,xmlHandler);
  236. inflateTextViewByBean(bean);
  237. }catch(IOExceptionie){
  238. ie.printStackTrace();
  239. }catch(ParserConfigurationExceptione){
  240. e.printStackTrace();
  241. }catch(SAXExceptione){
  242. e.printStackTrace();
  243. }catch(FactoryConfigurationErrore){
  244. e.printStackTrace();
  245. }finally{
  246. try{
  247. if(is!=null){
  248. is.close();
  249. }
  250. }catch(IOExceptionie){
  251. ie.printStackTrace();
  252. }
  253. }
  254. }
  255. classMyXMLHandlerextendsDefaultHandler{
  256. Beanbean;
  257. StringcurrentElement;
  258. publicMyXMLHandler(Beanbean){
  259. MyXMLHandler.this.bean=bean;
  260. }
  261. publicvoidstartDocument()throwsSAXException{
  262. Log.d(TAG,"MyXMLHandlerstartDocument");
  263. }
  264. publicvoidendDocument()throwsSAXException{
  265. Log.d(TAG,"MyXMLHandlerendDocument");
  266. }
  267. publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesatts)
  268. throwsSAXException{
  269. //Log.d(TAG,"MyXMLHandlerstartElement");
  270. currentElement=localName;
  271. if(localName.equals("item")){
  272. if(atts!=null){
  273. for(inti=0;i<atts.getLength();i++){
  274. //本例中atts.getLength()值为1
  275. bean.vecUrl.add(atts.getValue(i));
  276. Log.d(TAG,"addurl["+atts.getValue(i)+"]");
  277. }
  278. }
  279. }
  280. }
  281. publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{
  282. Stringstr=newString(ch,start,length);
  283. //Log.d(TAG,"MyXMLHandlercharactersstart="+start+"len="+
  284. //length+"str["+str
  285. //+"]");
  286. if(currentElement!=null){
  287. Stringtmp=newString(ch,start,length);
  288. if(currentElement.equals("title")){
  289. bean.title=tmp;
  290. }elseif(currentElement.equals("body")){
  291. bean.development_forum_name=tmp;
  292. }elseif(currentElement.equals("item")){
  293. bean.vecName.add(tmp);
  294. Log.d(TAG,"addname["+tmp+"]");
  295. }
  296. }
  297. }
  298. publicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{
  299. Log.d(TAG,"MyXMLHandlerendDocument");
  300. currentElement=null;
  301. }
  302. }
  303. classBean{
  304. Stringtype;
  305. Stringtitle;
  306. Stringdevelopment_forum_name;
  307. Vector<String>vecName;
  308. Vector<String>vecUrl;
  309. }
  310. }

本文内容归CSDN博客博主Sodino所有

转载请注明出处:http://blog.csdn.net/sodino/archive/2011/04/06/6305949.aspx


更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. Android(安卓)Manifest.xml解析
  3. Android(安卓)ApiDemos示例解析(78):Graphics->ScaleToFit
  4. Timber 源码解析
  5. Android(安卓)ApiDemos示例解析
  6. Android(安卓)ApiDemos示例解析(87):Media->MediaPlayer
  7. Android开发实践 Intent 解析
  8. Gson解析json,让json解析不再困难
  9. Android(安卓)init.rc文件解析过程详解(一)

随机推荐

  1. Android 选择图片、上传图片之PictureSel
  2. Android(安卓)设计原则【+整理】
  3. Android 如何在自定义界面上启用输入法 (
  4. java/android计算明天,今天,昨天,后天
  5. 为 Android* 设备构建动态 UI
  6. Android的多媒体框架OpenCore(PacketVide
  7. Android(安卓)Studio开发环境配置(无需上
  8. 《Android/OPhone开发完全讲义》连载(6):为T
  9. android列表【android开发记录片】androi
  10. android 使用自定义权限(1)