Android中Sax解析与Dom解析xml文件


<?xml version="1.0" encoding="UTF-8"?>
<persons>
<person id="23">
<name>李明</name>
<age>30</age>
</person>
<person id="20">
<name>李向梅</name>
<age>25</age>
</person>
<person id="24">
<name>常瑞鹏</name>
<age>65</age>
</person>
</persons>

------------------------------------------------------------------------------------------------------------------

Android中Sax解析与Dom解析xml文件Android中Sax解析与Dom解析xml文件Android中Sax解析与Dom解析xml文件Android中Sax解析与Dom解析xml文件

-------------------------------------------------------------------------------------------------------------------

package com.example.day03_xml.domain;



import java.io.Serializable;


public class Person implements Serializable{

/**

*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private short age;

public Person() {
super();
// TODO Auto-generated constructor stub
}


public Person(int id, String name, short age) {
super();
this.id = id;
this.name = name;
this.age = age;
}


public int getId() {
return id;
}


public void setId(int id) {
this.id = id;
}


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}


public short getAge() {
return age;
}


public void setAge(short age) {
this.age = age;
}



}

-------------------------------------------------------------------------------------------------------------------------------------------------

package com.example.day03_xml.service;


import java.util.ArrayList;
import java.util.List;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.example.day03_xml.domain.Person;


public class XMLContentHandlerService extends DefaultHandler {
// 解析的person对象储存到list集合中
private List<Person> persons;
// 解析当前person对象
public Person currenPerson;
// 声明标签名称
public String tagName;


public List<Person> getPersons() {
return persons;
}


public void setPersons(List<Person> persons) {
this.persons = persons;
}


@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
super.characters(ch, start, length);


// 首先判断tagName是否为空
if (tagName != null) {
// 获取标签中的内容
String data = new String(ch, start, length);
// 判断标签是否是name
if (tagName.equals("name")) {
currenPerson.setName(data);
} else if (tagName.equals("age")) {// 判断标签是否是age
currenPerson.setAge((short) Integer.parseInt(data));
}


}
}


@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
super.endElement(uri, localName, qName);


// 当person标签结束的时候 把person对象存储到集中
if (localName.equals("person")) {
persons.add(currenPerson);
// 当对象=null
currenPerson = null;
}


// person age
// name
this.tagName = null;
}


/**
* 文档开始触发的事件
*/
@Override
public void startDocument() throws SAXException {
super.startDocument();
persons = new ArrayList<Person>();
}


@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
super.startElement(uri, localName, qName, attributes);


// 判断解析的标签是否是person
if (localName.equals("person")) {
// 创建person对象
currenPerson = new Person();
// 把id属性的值解析出来 并且把id赋值给currentPerson对象
currenPerson.setId(Integer.parseInt(attributes.getValue(0)));
}
// person name age
this.tagName = localName;


}


public void endDocument() throws SAXException {
super.endDocument();
}


}

-----------------------------------------------------------------------------------------------------------------------------

package com.example.day03_xml.service;


import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


import com.example.day03_xml.domain.Person;


public class XMLDomService {


public List<Person> parseXML(InputStream is) {


List<Person> list = new ArrayList<Person>();


// 创建DOM工厂对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();


try {
// DocumentBuilder对象
DocumentBuilder builder = factory.newDocumentBuilder();


// 获取文档对象
Document document = builder.parse(is);


// 获取文档对象的root
Element root = document.getDocumentElement();


// 获取persons根节点中所有的person节点对象


NodeList personNodes = root.getElementsByTagName("person");


// 遍历所有的person节点
for (int i = 0; i < personNodes.getLength(); i++) {
Person person = new Person();


// 根据item(index)获取该索引对应的节点对象
Element personNode = (Element) personNodes.item(i); // 具体的person节点


// 设置id属性值
person.setId(Integer.parseInt(personNode.getAttribute("id")));


// 获取该节点下面的所有字节点
NodeList personChildNodes = personNode.getChildNodes();


// 遍历person的字节点
for (int index = 0; index < personChildNodes.getLength(); index++) {
// 获取子节点
Node node = personChildNodes.item(index);
// 判断node节点是否是元素节点
if (node.getNodeType() == Node.ELEMENT_NODE) {
// 把节点转换成元素节点
Element element = (Element) node;


// 判断元素节点是否是name元素节点
if ("name".equals(element.getNodeName())) {
person.setName(element.getFirstChild()
.getNodeValue());


} else if ("age".equals(element.getNodeName())) {


person.setAge(new Short(element.getFirstChild()
.getNodeValue()));
}


}


}
// 把person对象加入到集合中
list.add(person);


}
is.close();
} catch (Exception e) {


e.printStackTrace();
}


return list;
}
}

-----------------------------------------------------------------------------------------------------------------------------------------------------------

package com.example.day03_xml;


import java.io.IOException;
import java.io.InputStream;
import java.util.List;


import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;


import com.example.day03_xml.domain.Person;
import com.example.day03_xml.service.XMLContentHandlerService;
import com.example.day03_xml.service.XMLDomService;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {
public Button btn_sax, btn_dom, btn_pull;
public XMLDomService xmlDomService;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 设置显示的视图
setContentView(R.layout.activity_main);
// 实例化
xmlDomService = new XMLDomService();
// 通过findViewById方法获取控件对象
btn_sax = (Button) findViewById(R.id.btn_sax);
btn_dom = (Button) findViewById(R.id.btn_dom);
btn_pull = (Button) findViewById(R.id.btn_pull);


// 给按钮注册事件
btn_sax.setOnClickListener(new MyClickListener());
btn_dom.setOnClickListener(new MyClickListener());
btn_pull.setOnClickListener(new MyClickListener());


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


class MyClickListener implements View.OnClickListener {


@Override
public void onClick(View v) {


int id = v.getId();


switch (id) {
case R.id.btn_sax:


Toast.makeText(MainActivity.this, "采用sax解析xml",
Toast.LENGTH_LONG).show();


// sax解析的工厂对象
SAXParserFactory factory = SAXParserFactory.newInstance();
// 得到sax的解析器
try {
SAXParser saxParser = factory.newSAXParser();
// 创建handler对象
XMLContentHandlerService handlerService = new XMLContentHandlerService();


// 获取到了aserts目录中的csdn.xml文件
InputStream is = getAssets().open("csdn.xml");
// 直接解析 InputStream的流对象
saxParser.parse(is, handlerService);


// 通过 handlerService对象
Toast.makeText(MainActivity.this,
"---" + handlerService.getPersons().size(),
Toast.LENGTH_LONG).show();


} catch (Exception e) {


e.printStackTrace();
}


break;


case R.id.btn_dom:
Toast.makeText(MainActivity.this, "采用dom解析xml",
Toast.LENGTH_LONG).show();
InputStream is = null;


try {
is = getAssets().open("csdn.xml");
List<Person> persons = xmlDomService.parseXML(is);


Toast.makeText(MainActivity.this,
"" + persons.get(0).getName(), Toast.LENGTH_LONG)
.show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


case R.id.btn_pull:
Toast.makeText(MainActivity.this, "采用pull解析xml",
Toast.LENGTH_LONG).show();
break;
}


}


}
}

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.day03_xml"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.day03_xml.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>

-------------------------------------------------------------------------------------------------------------------------

<?xml version="1.0" encoding="utf-8"?>
<resources>


    <string name="app_name">day03-xml</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="btn_sax">采用sax解析</string>
    <string name="btn_dom">采用Dom解析xml</string>
    <string name="btn_pull">采用pull解析xml</string>


</resources>

----------------------------------------------------------------------------------------------------------------------

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >


    <Button
        android:id="@+id/btn_sax"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="18dp"
        android:text="@string/btn_sax" />


    <Button
        android:id="@+id/btn_dom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btn_sax"
        android:layout_alignRight="@+id/btn_sax"
        android:layout_below="@+id/btn_sax"
        android:layout_marginTop="65dp"
        android:text="@string/btn_dom" />


    <Button
        android:id="@+id/btn_pull"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btn_dom"
        android:layout_alignRight="@+id/btn_dom"
        android:layout_below="@+id/btn_dom"
        android:layout_marginTop="69dp"
        android:text="@string/btn_pull" />


</RelativeLayout>


 

你可能感兴趣的:(dom解析xml)