Android中XML解析-Dom解析

简介:

Android中需要解析服务器端传过来的数据,由于XML是与平台无关的特性,被广泛运用于数据通信中,有的时候需要解析xml数据,格式有三种方式,分别是DOM、SAX以及PULL三种方式,本文就简单以Dom解析为例,解析XML, DOM方式解析xml是先把xml文档都读到内存中,然后再用DOM API来访问树形结构,并获取数据的,但是这样一来,如果xml文件很大,手机CPU处理能力比PC差,因此在处理效率方面就相对差了,使用Dom解析就不是太合适了。

基础维护

首先下assets目录下新建一个Book.xml文件:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<?xml version= "1.0"  encoding= "utf-8" ?>
<Books>
 
     <Book name= "康师傅的亿万帝国"  >
 
         <Title>
     据周元根的小学同学回忆,大约 7 岁那年,周元根开始读小学,由于和别人重名,于是改了名字。但他在村里一直沿用“周元根”这个名字,周家祖坟的 5 块墓碑上,刻的也是“周元根”这个名字。
         
         </Title>
 
         <Picture>
      http: //p.qpic.cn/ninja/0/ninja1406636943/0
         
         </Picture>
     </Book>
 
     <Book name= "徐才厚受贿额特别巨大"  >
 
         <Title>
    根据最高人民检察院授权,军事检察院对中央军委原副主席徐才厚以涉嫌受贿犯罪立案侦查。 2014 10 27 日,对该案侦查终结,移送审查起诉。
 
         </Title>
 
         <Picture>
http: //www.sinaimg.cn/dy/slidenews/1_img/2014_44/2841_506865_709392.jpg
         
         </Picture>
     </Book>
     <Book name= "发改委副司长魏鹏远"  >
 
         <Title>
     最高人民检察院反贪污贿赂总局局长徐进辉今日表示,煤炭司副司长魏鹏远家中搜查发现现金折合人民币 2 亿余元,成为建国以来检察机关一次起获赃款现金数额最大的案件。
 
         </Title>
 
         <Picture>
     http: //img1.cache.netease.com/catchpic/D/DC/DCB2315FD0F50C665BB1474768192642.jpg
 
         </Picture>
     </Book>
 
</Books>

 

XML存储的方式其实和类存储的是类似的,这个时候建一个对应的Book类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public  class  Book {
     private  String title;
     private  String picture;
     private  String name;
     public  String getName() {
         return  name;
     }
     public  void  setName(String name) {
         this .name = name;
     }
     public  String getTitle() {
         return  title;
     }
     public  void  setTitle(String title) {
         this .title = title;
     }
     public  String getPicture() {
         return  picture;
     }
     public  void  setPicture(String picture) {
         this .picture = picture;
     }
}

 Book布局文件:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?xml version= "1.0"  encoding= "utf-8" ?>
<LinearLayout xmlns:android= "http://schemas.android.com/apk/res/android"
     android:layout_width= "match_parent"
     android:layout_height= "wrap_content"
     android:orientation= "horizontal"  >
 
     <ImageView
         android:id= "@+id/itemImage"
         android:layout_width= "40dp"
         android:layout_height= "60dp"
         android:src= "@drawable/fight"
        />
 
     <LinearLayout
         android:layout_width= "match_parent"
         android:layout_height= "wrap_content"
         android:orientation= "vertical"
         android:paddingLeft= "10dp"
        >
 
         <TextView
             android:id= "@+id/itemTitle"
             android:layout_width= "match_parent"
             android:layout_height= "wrap_content"
             android:text= "标题"
             android:textSize= "18sp"  />
 
         <TextView
             android:id= "@+id/itemText"
             android:layout_width= "match_parent"
             android:layout_height= "wrap_content"
             android:textSize= "12sp"
             android:text= "xxxxxxxxx"  />
     </LinearLayout>
 
</LinearLayout>

 

Demo实现

 

现在最主要的是将XML的Book转换成一个Book集合:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
public  List<Book> getBooks(InputStream stream) {
     List<Book> list =  new  ArrayList<Book>();
     DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
     try  {
         DocumentBuilder builder = factory.newDocumentBuilder();
         // 获取XML文档结构
         Document document = builder.parse(stream);
         // 获取根节点
         Element rootElement = document.getDocumentElement();
         NodeList nodeList = rootElement.getElementsByTagName( "Book" );
         for  ( int  i =  0 ; i < nodeList.getLength(); i++) {
             Book book =  new  Book();
             // Node转成Element
             Element element = (Element) nodeList.item(i);
             book.setName(element.getAttribute( "name" ));
             Element eleTitlElement = (Element) element
                     .getElementsByTagName( "Title" ).item( 0 );
             String title = eleTitlElement.getFirstChild().getNodeValue();
             Element elePicElement = (Element) element.getElementsByTagName(
                     "Picture" ).item( 0 );
             String picString = elePicElement.getFirstChild().getNodeValue();
             book.setTitle(title);
             book.setPicture(picString);
             list.add(book);
         }
     catch  (ParserConfigurationException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     catch  (SAXException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     catch  (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
     }
     return  list;
 
}

 1.通过DocumentBuilderFactory工厂类实例化一个工厂,通过工厂的newDocumentBuilder()方法实例化一个DocumentBuilder .通过创建好的 DocumentBuilder 对象的 parse(InputStream) 方法就可以解析我们的xml文档,然后返回的是一个Document的对象,这个Document对象代表的就是我们的整个xml文档。

2.获取整个xml的Document对象后,我们可以获得其下面的各个元素节点(Element),同样每个元素节点可能又有多个属性(Attribute),根据每个元素节点我们又可以遍历该元素节点下面的子节点等等。

MainActivity启动方法中的调用:

 

1
2
3
4
5
6
7
8
9
10
11
12
InputStream inputStream =  null ;
try  {
     inputStream = inputStream = MainActivity. this .getResources().getAssets().open( "Book.xml" );
catch  (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
}
 
list = getBooks(inputStream);
View view = getLayoutInflater().inflate(R.layout.activity_main,  null );
ListView listView = (ListView) findViewById(R.id.list_dom);
listView.setAdapter( new  testAdapter());

 

testAdapter的写法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class  testAdapter  extends  BaseAdapter {
 
     @Override
     public  int  getCount() {
         // TODO Auto-generated method stub
         return  list.size();
     }
 
     @Override
     public  Object getItem( int  position) {
         // TODO Auto-generated method stub
         return  null ;
     }
 
     @Override
     public  long  getItemId( int  position) {
         // TODO Auto-generated method stub
         return  0 ;
     }
 
     @Override
     public  View getView( int  position, View convertView, ViewGroup parent) {
         Book book = (Book) list.get(position);
         View view =  null ;
         if  (convertView ==  null ) {
             LayoutInflater layoutInflater = getLayoutInflater();
             view = layoutInflater.inflate(R.layout.book,  null );
         else  {
             view = convertView;
         }
         // ImageView imageView = (ImageView)
         // view.findViewById(R.id.itemImage);
 
         // imageView.setImageResource(BIND_ABOVE_CLIENT);
         TextView titleView = (TextView) view.findViewById(R.id.itemTitle);
         titleView.setText(book.getName());
 
         TextView contentView = (TextView) view.findViewById(R.id.itemText);
         contentView.setText(book.getTitle());
         return  view;
     }
 
}

 本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4066444.html,如需转载请自行联系原作者

相关文章
|
4天前
|
XML API PHP
Android使用XML-RPC实现blog客户端
Android使用XML-RPC实现blog客户端
10 2
|
6天前
|
Java Android开发
Android12 双击power键启动相机源码解析
Android12 双击power键启动相机源码解析
20 0
|
2天前
|
XML Web App开发 JavaScript
XML DOM 解析器
XML解析器是浏览器内置的工具,用于将XML转换为JavaScript可操作的XML DOM对象。这个DOM包含遍历、修改XML节点的函数。首先,XML文档需加载到DOM中,通过XMLHttpRequest对象实现,如示例所示:根据浏览器类型创建XMLHTTP对象,打开并发送GET请求到服务器获取&quot;books.xml&quot;,然后将响应转化为DOM对象。
|
3天前
|
XML Web App开发 JavaScript
XML DOM 解析器
XML解析器是浏览器内置的工具,用于将XML转换为JavaScript可操作的XML DOM对象。通过DOM,可以进行节点的遍历、访问和修改。以下JS代码示例展示了如何加载XML文档&quot;books.xml&quot;:首先检查XMLHttpRequest支持,然后创建请求对象,打开并发送GET请求,最后将响应转化为DOM对象。
|
4天前
|
Android开发
android string.xml文件中的整型和string型代替
android string.xml文件中的整型和string型代替
|
4天前
|
XML JavaScript 数据格式
Beautiful Soup 库的工作原理基于解析器和 DOM(文档对象模型)树的概念
【5月更文挑战第10天】Beautiful Soup 使用解析器(如 html.parser, lxml, html5lib)解析HTML/XML文档,构建DOM树。它提供方法查询和操作DOM,如find(), find_all()查找元素,get_text(), get()提取信息。还能修改DOM,添加、修改或删除元素,并通过prettify()输出格式化字符串。它是处理网页数据的利器,尤其在处理不规则结构时。
11 2
|
4天前
|
XML Web App开发 JavaScript
XML DOM 解析器
XML解析器是浏览器内置工具,用于将XML转换为JavaScript可操作的XML DOM对象,允许遍历、修改节点。大多数现代浏览器支持这一功能。以下JS代码示例展示了如何加载XML文档&quot;books.xml&quot;
|
4天前
|
XML JavaScript Java
详解Java解析XML的四种方法
详解Java解析XML的四种方法
|
3天前
PandasTA 源码解析(二十三)
PandasTA 源码解析(二十三)
28 0
|
3天前
PandasTA 源码解析(二十二)(3)
PandasTA 源码解析(二十二)
24 0

推荐镜像

更多