Android中XML的解析 使用PULL

2021-09-12 00:25:31 字數 2426 閱讀 8207

android中一般有三種方式解析xml:****** api for xml(sax) 、 document object model(dom)和android附帶的pull解析器,這次我就來分享一下使用pull解析器來解析xml。

可以選擇在asset中建立個xml,也可以在res資料夾中新增,這裡我採用的第二種方法,在res中新建了乙個xml資料夾,新增了個xml,//然後洗淨切絲備用。

xml中就隨便寫了寫:

1.用啥子來解析呢?

開頭說了,我們使用pull解析器:xmlpullparser,不過使用這個需要pull的jar包,所以我們可以換乙個:xmlresourceparser,這個是android自帶的。

/**

* the xml parsing inte***ce returned for an xml resource. this is a standard

* xmlpullparser inte***ce, as well as an extended attributeset inte***ce and

* an additional close() method on this inte***ce for the client to indicate

* when it is done reading the resource.

*/public inte***ce xmlresourceparser extends xmlpullparser, attributeset, autocloseable

複製**

可以看出來,xmlresourceparser繼承自xmlpullparser。

現在我們廚具(xmlresourceparser)有了,食材(xml檔案)也齊了,那麼可以直接上了麼?不過,是不是缺了個盤子來盛菜。

2.準備個類來放解析出的資料

其實這步驟不做也可以(就著鍋來吃,那不是就成火鍋了麼),我這裡還是囉嗦一下,建立了item類。

class item 

public string gettitle()

public void settitle(string title)

public int gettype()

public void settype(int type)

@override

public string tostring()

}複製**

這個類沒什麼好說的(我重寫tostring方法也就為了之後顯示結果方便點)。

3. 先看看食譜,怎麼解析的

解析的原理是:解析器(parser)讀取乙個tag,解析後返回這個tag的eventtype(有10種,之後說明),而我們通過判斷不同型別採取對應操作。

10種eventtype

"start_document",

"end_document",

"start_tag",

"end_tag",

"text",

"cdsect",

"entity_ref",

"ignorable_whitespace",

"processing_instruction",

"comment",

"docdecl"

我們可以重點關注這四個,start_document:xml文件的開頭,end_document文件結束標誌,start_tag:tag開始標誌,比如,end_tag:tag結束標誌,比如

多說無益,放碼過來

這句會丟擲異常,那我們就直接上拋異常吧

public listparse(xmlresourceparser parser) throws exception else if ("title".equals(parser.getname()))

break;

//碰到tag的結尾

case xmlpullparser.end_tag:

if ("item".equals(parser.getname()))

break;

default://寫個default,好習慣

break;

}//結束,下乙個

eventtype = parser.next();

}return items;

}複製**

4.準備就緒,解析吧
listitems;

try

} catch (exception e)

複製**

o了個輪詢排程演算法k

android中解析XML檔案

上面這個鏈結詳細介紹了幾種xml的解析方法以及原理。下面是實現思路 1.讀取xml檔案 2.獲取讀取事件,如果檔案結束,則停止解析 3.處理讀取事件 4.回到第二步。下面是實現過程 1.要解析的xml檔案內容 name jim age 123 gender male email mail hostn...

Android中pull解析xml檔案

注意區分下面兩種方法 xml.newserializer 序列化器 xml.newpullparser pull解析器 xml檔案解析有sax,dom,pull解析三種方法 pull解析的過程 1,在assets資料夾下拿到將要解析的xml檔案 2,獲取xml解析器newpullparser 3,設...

android解析XML檔案

對於config.xml 1.dom方式 public void getbydom catch saxexception ex catch ioexception ex catch parserconfigurationexception ex 2.pull方式 public void getbyp...