[Android]四种方式解析字符串----JSON、SAX、DOM、XML
16lz
2021-01-26
当是练习吧,分别以JSON、SAX、DOM、XML(android.util.XML)来解析字符串。
个人感觉这四种方式的实现由难到易的顺序是:SAX→XML→DOM→JSON。
JSON解析的内容如下,文件名为devdiv.json,存于工程的assets目录下:
[xhtml] view plain copy- {
- "code":"1",
- "result":{
- "title":"Devdiv移动开发社区",
- "title_url":"http://www.devdiv.com/forum.php",
- "development_forum_name":"开发讨论区",
- "development_forum":[
- {"name":"WindowsPhone论坛","url":"http://www.devdiv.com/forum-windows-phone-mobile-1.html"},
- {"name":"Android论坛","url":"http://www.devdiv.com/forum-android-1.html"},
- {"name":"iOS/iPhone论坛","url":"http://www.devdiv.com/forum-iphone-1.html"}
- ]
- }
- }
剩下三个解析内容如下,文件名为devdiv.xml,存于工程的assets目录下:
[xhtml] view plain copy- <root>
- <title>Devdiv移动开发社区</title>
- <body>开发讨论区</body>
- <itemurl="http://www.devdiv.com/forum-windows-phone-mobile-1.html">WindowsPhone论坛</item>
- <itemurl="http://www.devdiv.com/forum-android-1.html">Android论坛</item>
- <itemurl="http://www.devdiv.com/forum-iphone-1.html">iOS/iPhone论坛</item>
- </root>
本例子解析后显示效果:
对于DOM的解析,在SDK8及以上版本有两种方法。代码如下:
[java] view plain copy- packagelab.sodino.string;
- importjava.io.IOException;
- importjava.io.InputStream;
- importjava.util.Vector;
- importjavax.xml.parsers.DocumentBuilder;
- importjavax.xml.parsers.DocumentBuilderFactory;
- importjavax.xml.parsers.FactoryConfigurationError;
- importjavax.xml.parsers.ParserConfigurationException;
- importjavax.xml.parsers.SAXParser;
- importjavax.xml.parsers.SAXParserFactory;
- importorg.json.JSONArray;
- importorg.json.JSONException;
- importorg.json.JSONObject;
- importorg.w3c.dom.Document;
- importorg.w3c.dom.Element;
- importorg.w3c.dom.Node;
- importorg.w3c.dom.NodeList;
- importorg.xml.sax.Attributes;
- importorg.xml.sax.SAXException;
- importorg.xml.sax.helpers.DefaultHandler;
- importandroid.app.Activity;
- importandroid.graphics.Typeface;
- importandroid.os.Build;
- importandroid.os.Bundle;
- importandroid.text.SpannableString;
- importandroid.text.Spanned;
- importandroid.text.method.LinkMovementMethod;
- importandroid.text.style.StyleSpan;
- importandroid.text.style.URLSpan;
- importandroid.util.Log;
- importandroid.view.View;
- importandroid.widget.Button;
- importandroid.widget.TextView;
- publicclassTextActextendsActivity{
- publicstaticfinalStringTAG="ANDROID_LAB";
- privateButtonbtnJSON;
- privateButtonbtnSAX;
- privateButtonbtnDOM;
- privateButtonbtnXML;
- privateBtnListenerbtnListener;
- privateTextViewtxtInfo;
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- btnListener=newBtnListener();
- btnDOM=(Button)findViewById(R.id.btnDOM);
- btnDOM.setOnClickListener(btnListener);
- txtInfo=(TextView)findViewById(R.id.txtInfo);
- }
- privatevoidinflateTextViewByBean(Beanbean){
- intspanCount=4;
- int[]start=newint[spanCount];
- int[]end=newint[spanCount];
- StringBufferbuffer=newStringBuffer();
- buffer.append(bean.type+"/n");
- buffer.append(bean.title+"/n");
- start[0]=buffer.length();
- buffer.append(bean.development_forum_name+"/n");
- end[0]=buffer.length();
- for(inti=0;i<bean.vecName.size();i++){
- start[i+1]=buffer.length();
- buffer.append(bean.vecName.get(i)+"/n");
- end[i+1]=buffer.length();
- }
- SpannableStringspannableString=newSpannableString(buffer.toString());
- spannableString.setSpan(newStyleSpan(Typeface.ITALIC),start[0],end[0],
- Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- for(inti=0;i<bean.vecName.size();i++){
- spannableString.setSpan(newURLSpan(bean.vecUrl.get(i)),start[i+1],end[i+1],
- Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
- }
- txtInfo.setText(spannableString);
- txtInfo.setMovementMethod(LinkMovementMethod.getInstance());
- }
- classBtnListenerimplementsButton.OnClickListener{
- publicvoidonClick(Viewview){
- if(view==btnJSON){
- showInfoFromJSON();
- }elseif(view==btnSAX){
- showInfoFromSAXParser();
- }elseif(view==btnDOM){
- showInfoFromDOM();
- }elseif(view==btnXML){
- showInfoFromXML();
- }
- }
- }
- publicvoidshowInfoFromJSON(){
- Beanbean=newBean();
- bean.type="InflatedbyJSON/n";
- Stringcontent="";
- InputStreamis=null;
- try{
- is=getAssets().open("devdiv.json");
- byte[]data=newbyte[is.available()];
- is.read(data);
- content=newString(data);
- Log.d(TAG,"content="+content);
- JSONObjectjsonContent=newJSONObject(content);
- intcode=jsonContent.getInt("code");
- //假设默认code为1时才是正确的json数据。
- if(code==1){
- JSONObjectjsonResult=jsonContent.getJSONObject("result");
- bean.title=jsonResult.getString("title");
- bean.development_forum_name=jsonResult.getString("development_forum_name");
- bean.vecName=newVector<String>();
- bean.vecUrl=newVector<String>();
- JSONArraydevArr=jsonResult.getJSONArray("development_forum");
- Stringtmp="";
- for(inti=0;i<devArr.length();i++){
- JSONObjectobj=devArr.getJSONObject(i);
- tmp=obj.getString("name");
- bean.vecName.add(tmp);
- tmp=obj.getString("url");
- bean.vecUrl.add(tmp);
- }
- inflateTextViewByBean(bean);
- }else{
- Log.d(TAG,"Aerroroccurwhenparseajsonfile.");
- }
- }catch(IOExceptione){
- e.printStackTrace();
- }catch(JSONExceptione){
- e.printStackTrace();
- }finally{
- try{
- if(is!=null){
- is.close();
- }
- }catch(IOExceptionie){
- ie.printStackTrace();
- }
- }
- }
- publicvoidshowInfoFromXML(){
- Beanbean=newBean();
- bean.type="InflatedbyXML/n";
- bean.vecName=newVector<String>();
- bean.vecUrl=newVector<String>();
- MyXMLHandlerxmlHandler=null;
- InputStreamis=null;
- xmlHandler=newMyXMLHandler(bean);
- try{
- is=getAssets().open("devdiv.xml");
- //一句话就OK了。
- android.util.Xml.parse(is,android.util.Xml.Encoding.UTF_8,xmlHandler);
- }catch(IOExceptione){
- e.printStackTrace();
- }catch(SAXExceptione){
- e.printStackTrace();
- }finally{
- try{
- if(is!=null){
- is.close();
- }
- }catch(IOExceptionie){
- ie.printStackTrace();
- }
- }
- inflateTextViewByBean(bean);
- }
- publicvoidshowInfoFromDOM(){
- Beanbean=newBean();
- bean.type="InflatedbyDOM/n";
- bean.vecName=newVector<String>();
- bean.vecUrl=newVector<String>();
- InputStreamis=null;
- DocumentBuilderFactorydomFactory=DocumentBuilderFactory.newInstance();
- try{
- is=getAssets().open("devdiv.xml");
- NodeListlist=null;
- DocumentBuilderdomBuilder=domFactory.newDocumentBuilder();
- Documentdoc=domBuilder.parse(is);
- //获取根目录
- ElementrootElement=doc.getDocumentElement();
- //输出[rootElement=root]
- Log.d(TAG,"rootElement="+rootElement.getNodeName());
- list=rootElement.getElementsByTagName("title");
- if(Integer.parseInt(Build.VERSION.SDK)>=8){
- //在已提前获只有一个title的情况下直接去取list.item(0)
- bean.title=list.item(0).getTextContent();
- //在已提前获只有一个body的情况下直接去取list.item(0)
- list=rootElement.getElementsByTagName("body");
- bean.development_forum_name=list.item(0).getTextContent();
- //多个item的读取情形
- list=rootElement.getElementsByTagName("item");
- for(inti=0;i<list.getLength();i++){
- Nodenode=list.item(i);
- bean.vecUrl.add(node.getAttributes().item(0).getTextContent());
- bean.vecName.add(node.getTextContent());
- }
- }else{
- //在已提前获只有一个title的情况下直接去取list.item(0)
- bean.title=list.item(0).getFirstChild().getNodeValue();
- //在已提前获只有一个body的情况下直接去取list.item(0)
- list=rootElement.getElementsByTagName("body");
- bean.development_forum_name=list.item(0).getFirstChild().getNodeValue();
- //多个item的读取情形
- list=rootElement.getElementsByTagName("item");
- for(inti=0;i<list.getLength();i++){
- Nodenode=list.item(i);
- bean.vecUrl.add(node.getAttributes().getNamedItem("url").getNodeValue());
- bean.vecName.add(node.getFirstChild().getNodeValue());
- }
- }
- }catch(ParserConfigurationExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }catch(SAXExceptione){
- e.printStackTrace();
- }finally{
- try{
- if(is!=null){
- is.close();
- }
- }catch(IOExceptionie){
- ie.printStackTrace();
- }
- }
- inflateTextViewByBean(bean);
- }
- publicvoidshowInfoFromSAXParser(){
- Beanbean=newBean();
- bean.vecName=newVector<String>();
- bean.vecUrl=newVector<String>();
- bean.type="InflatedbySAXParser/n";
- InputStreamis=null;
- SAXParserparser=null;
- MyXMLHandlerxmlHandler=null;
- try{
- parser=SAXParserFactory.newInstance().newSAXParser();
- xmlHandler=newMyXMLHandler(bean);
- is=getAssets().open("devdiv.xml");
- parser.parse(is,xmlHandler);
- inflateTextViewByBean(bean);
- }catch(IOExceptionie){
- ie.printStackTrace();
- }catch(ParserConfigurationExceptione){
- e.printStackTrace();
- }catch(SAXExceptione){
- e.printStackTrace();
- }catch(FactoryConfigurationErrore){
- e.printStackTrace();
- }finally{
- try{
- if(is!=null){
- is.close();
- }
- }catch(IOExceptionie){
- ie.printStackTrace();
- }
- }
- }
- classMyXMLHandlerextendsDefaultHandler{
- Beanbean;
- StringcurrentElement;
- publicMyXMLHandler(Beanbean){
- MyXMLHandler.this.bean=bean;
- }
- publicvoidstartDocument()throwsSAXException{
- Log.d(TAG,"MyXMLHandlerstartDocument");
- }
- publicvoidendDocument()throwsSAXException{
- Log.d(TAG,"MyXMLHandlerendDocument");
- }
- publicvoidstartElement(Stringuri,StringlocalName,StringqName,Attributesatts)
- throwsSAXException{
- //Log.d(TAG,"MyXMLHandlerstartElement");
- currentElement=localName;
- if(localName.equals("item")){
- if(atts!=null){
- for(inti=0;i<atts.getLength();i++){
- //本例中atts.getLength()值为1
- bean.vecUrl.add(atts.getValue(i));
- Log.d(TAG,"addurl["+atts.getValue(i)+"]");
- }
- }
- }
- }
- publicvoidcharacters(char[]ch,intstart,intlength)throwsSAXException{
- Stringstr=newString(ch,start,length);
- //Log.d(TAG,"MyXMLHandlercharactersstart="+start+"len="+
- //length+"str["+str
- //+"]");
- if(currentElement!=null){
- Stringtmp=newString(ch,start,length);
- if(currentElement.equals("title")){
- bean.title=tmp;
- }elseif(currentElement.equals("body")){
- bean.development_forum_name=tmp;
- }elseif(currentElement.equals("item")){
- bean.vecName.add(tmp);
- Log.d(TAG,"addname["+tmp+"]");
- }
- }
- }
- publicvoidendElement(Stringuri,StringlocalName,StringqName)throwsSAXException{
- Log.d(TAG,"MyXMLHandlerendDocument");
- currentElement=null;
- }
- }
- classBean{
- Stringtype;
- Stringtitle;
- Stringdevelopment_forum_name;
- Vector<String>vecName;
- Vector<String>vecUrl;
- }
- }
本文内容归CSDN博客博主Sodino所有
转载请注明出处:http://blog.csdn.net/sodino/archive/2011/04/06/6305949.aspx
更多相关文章
- SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
- Android(安卓)Manifest.xml解析
- Android(安卓)ApiDemos示例解析(78):Graphics->ScaleToFit
- Timber 源码解析
- Android(安卓)ApiDemos示例解析
- Android(安卓)ApiDemos示例解析(87):Media->MediaPlayer
- Android开发实践 Intent 解析
- Gson解析json,让json解析不再困难
- Android(安卓)init.rc文件解析过程详解(一)