Android中XML解析-Dom解析

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

基础维护

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

<?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类:

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布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <ImageView
        android:
        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:
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="标题"
            android:textSize="18sp" />

        <TextView
            android:
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="12sp" 
            android:text="xxxxxxxxx" />
    </LinearLayout>

</LinearLayout>

Demo实现

Android中XML解析-Dom解析

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

	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启动方法中的调用:

		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的写法:

	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;
		}

	}

周末看博客的都是好孩子,祝大家周末愉快~