Android 建立與解析XML(四)——詳解Pull方式_Android

來源:互聯網
上載者:User

 1、Pull概述

Android系統中和建立XML相關的包為org.xmlpull.v1,在這個包中不僅提供了用於建立XML的 XmlSerializer,還提供了用來解析XML的Pull方式解析器 XmlPullParser

XmlSerializer沒有像XmlPullParser那樣提取XML事件,而是把它們推出到資料流OutputStream或Writer中。

XmlSerializer提供了很直觀的API,即使用startDocument開始文檔,endDocument結束文檔,startTag開始元素,endTag結束元素,text添加文本等。

Pull方式建立XML,應用了標準xml構造器 org.xmlpull.v1.XmlSerializer來建立 XML ,org.xmlpull.v1.XmlPullParser來解析XML,需要匯入以下內容

org.xmlpull.v1

  • org.xmlpull.v1.XmlPullParser;
  • org.xmlpull.v1.XmlPullParserException;
  • org.xmlpull.v1.XmlPullParserFactory;
  • org.xmlpull.v1.XmlSerializer;

Pull 建立和解析 XML 的效果圖:

2、Pull 建立 XML

pull方式,建立xml是通過 XmlSerializer 類實現

首先,通過XmlSerializer得到建立xml的執行個體 xmlSerializer

接著,通過 xmlSerializer 設定輸出 xmlSerializer.setOutput,xmlSerializer.startDocument("utf-8", null)設定xml屬性等

然後,通過 xmlSerializer 建立 startDocument、startTag、text、endTag、endDocument等

 /** Pull方式,建立 XML */   public String pullXMLCreate(){     StringWriter xmlWriter = new StringWriter();      Person []persons = new Person[3];    // 建立節點Person對象     persons[0] = new Person(1, "sunboy_2050", "http://blogcsdnnet/sunboy_2050");     persons[1] = new Person(2, "baidu", "http://wwwbaiducom");     persons[2] = new Person(3, "google", "http://wwwgooglecom");          try { //     // 方式一:使用Android提供的工具 + 生產力類androidutilXml //     XmlSerializer xmlSerializer = XmlnewSerializer();                 // 方式二:使用工廠類XmlPullParserFactory的方式       XmlPullParserFactory factory = XmlPullParserFactorynewInstance();       XmlSerializer xmlSerializer = factorynewSerializer();              xmlSerializersetOutput(xmlWriter);       // 儲存建立的xml              xmlSerializersetFeature("http://xmlpullorg/v1/doc/featureshtml#indent-output", true); //     xmlSerializersetProperty("http://xmlpullorg/v1/doc/propertieshtml#serializer-indentation", " ");     // 設定屬性 //     xmlSerializersetProperty("http://xmlpullorg/v1/doc/propertieshtml#serializer-line-separator", "\n");       xmlSerializerstartDocument("utf-8", null);   // <?xml version='0' encoding='UTF-8' standalone='yes' ?>               xmlSerializerstartTag("", "root");       xmlSerializerattribute("", "author", "homer");       xmlSerializerattribute("", "date", "2012-04-28");              int personsLen = personslength;       for(int i=0; i<personsLen; i++) {         xmlSerializerstartTag("", "person");    // 建立person節點                  xmlSerializerstartTag("", "id");         xmlSerializertext(persons[i]getId()+"");         xmlSerializerendTag("", "id");          xmlSerializerstartTag("", "name");         xmlSerializertext(persons[i]getName());         xmlSerializerendTag("", "name");          xmlSerializerstartTag("", "blog");         xmlSerializertext(persons[i]getBlog());         xmlSerializerendTag("", "blog");                  xmlSerializerendTag("", "person");       }              xmlSerializerendTag("", "root");       xmlSerializerendDocument();            } catch (XmlPullParserException e) {    // XmlPullParserFactorynewInstance       eprintStackTrace();     } catch (IllegalArgumentException e) {   // xmlSerializersetOutput       eprintStackTrace();     } catch (IllegalStateException e) {     // xmlSerializersetOutput       eprintStackTrace();     } catch (IOException e) {    // xmlSerializersetOutput       eprintStackTrace();     } catch (Exception e) {       eprintStackTrace();     }          savedXML(fileName, xmlWritertoString());     return xmlWritertoString();   } 

運行結果:

3、Pull 解析 XML

pull方式,解析xml是通過 XmlPullParser 類實現

首先,通過XmlPullParser得到解析xml的執行個體 xpp

接著,通過 xpp設定輸入 xpp.setInput(is, "utf-8"),聲明定義儲存xml資訊的資料結構(如:Person數組)

然後,通過 xpp 解析 START_DOCUMENT、START_TAG、TEXT、END_TAG、END_DOCUMENT等
  

 /** Pull方式,解析 XML */   public String pullXMLResolve(){     StringWriter xmlWriter = new StringWriter();          InputStream is = readXML(fileName);     try { //     // 方式一:使用Android提供的工具 + 生產力類androidutilXml //     XmlPullParser xpp = XmlnewPullParser();              // 方式二:使用工廠類XmlPullParserFactory的方式       XmlPullParserFactory factory = XmlPullParserFactorynewInstance();       XmlPullParser xpp = factorynewPullParser();              xppsetInput(is, "utf-8");              List<Person> personsList = null;   // 儲存xml的person節點       Person person = null;       StringBuffer xmlHeader = null;     // 儲存xml頭部       String ele = null;   // Element flag              int eventType = xppgetEventType();       while(XmlPullParserEND_DOCUMENT != eventType) {         switch (eventType) {         case XmlPullParserSTART_DOCUMENT:           personsList = new ArrayList<Person>();    // 初始化persons           xmlHeader = new StringBuffer();       // 初始化xmlHeader           break;                    case XmlPullParserSTART_TAG:           if("root"equals(xppgetName())) {             String attrAuthor = xppgetAttributeValue(0);             String attrDate = xppgetAttributeValue(1);             xmlHeaderappend("root")append("\t\t");             xmlHeaderappend(attrAuthor)append("\t");             xmlHeaderappend(attrDate)append("\n");           } else if("person"equals(xppgetName())) {             person = new Person();     // 建立person執行個體           } else if("id"equals(xppgetName())) {             ele = "id";           } else if("name"equals(xppgetName())) {             ele = "name";           } else if("blog"equals(xppgetName())) {             ele = "blog";           } else {             ele = null;           }           break;                    case XmlPullParserTEXT:           if(null != ele) {             if("id"equals(ele)) {               personsetId(IntegerparseInt(xppgetText()));             } else if("name"equals(ele)) {               personsetName(xppgetText());             } else if("blog"equals(ele)) {               personsetBlog(xppgetText());             }           }           break;                    case XmlPullParserEND_TAG:           if("person"equals(xppgetName())){             personsListadd(person);             person = null;           }           ele = null;           break;         }                  eventType = xppnext();   // 下一個事件類型       }              xmlWriterappend(xmlHeader);       int personsLen = personsListsize();       for(int i=0; i<personsLen; i++) {         xmlWriterappend(personsListget(i)toString());       }            } catch (XmlPullParserException e) {    // XmlPullParserFactorynewInstance       eprintStackTrace();     } catch (Exception e) {       eprintStackTrace();     }          return xmlWritertoString();       } 

運行結果:

4、Person類

請參見前面部落格 Android 建立與解析XML(二)—— Dom方式 【4、Person類】

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.