【Android高级】XMl文件的DOM、SAX、PULL三种解析方式全解

前端之家收集整理的这篇文章主要介绍了【Android高级】XMl文件的DOM、SAX、PULL三种解析方式全解前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

本来一直忙着期末考试的复习,但复习挺无聊的,偶然看到xml的解析方法,虽然以前做过,但感觉不是很熟悉了,所以抽点时间一口气把三种方式都复习了遍。这三种方法中DOM最耗内存,因为它是把整个文件加载进去然后进行分类整理的,PULL和SAX类似,只是SAX要用到一个解析类,类中的主要三个方法完成内容的解析,而PULL方法是Android特有的,根据获得的标签判断并解析,这也是安卓中最常使用的方法

接下来给大家复习下,因为我觉得看代码更容易明白,讲解的就不多了。

首先我们准备好我们要解析的资源文件和封装好的javaBean。

person.xml

<?xml version="1.0" encoding="UTF-8"?>  
<persons>
    <person id="1">
        <name>sax</name>
        <age>12</age>
    </person>
    <person id="2">
        <name>ganganrou</name>
        <age>17</age>
    </person>
    <person id="3">
        <name>nuanwozi</name>
        <age>5</age>
    </person>
</persons>

封装好的javaBean
public class PersonBean {
	int id;
	String name;
	String 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 String getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "PersonBean [id=" + id + ",name=" + name + ",age=" + age + "]";
	}

}

接下来我们分别以DOM、SAX、PULL的方式对person.xml文件进行解析并封装到javaBean中去:

一、DOM

	public static List<PersonBean> getPersonBeans() {
		List<PersonBean> list = new ArrayList<PersonBean>();
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory
				.newInstance();
		try {
			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(DomPaserHelper.class
					.getClassLoader().getResourceAsStream("person2.xml"));
			Element element = document.getDocumentElement();
			NodeList nodeList = element.getElementsByTagName("person");

			for (int i = 0; i < nodeList.getLength(); i++) {
				Element node = (Element) nodeList.item(i);
				PersonBean bean = new PersonBean();
				bean.setId(Integer.valueOf(node.getAttribute("id")));

				NodeList list2 = node.getChildNodes();
				for (int j = 0; j < list2.getLength(); j++) {

					Node element2 = list2.item(j);

					<span style="color:#ff6600;">// 判断子Note的类型为元素Note</span>
					if (element2.getNodeType() == Node.ELEMENT_NODE) {
						Element childElement = (Element) element2;

						if ("name".equals(childElement.getNodeName())) {
							bean.setName(childElement.<span style="color:#ff6600;">getFirstChild</span>()
									.getNodeValue());
						}

						if ("age".equals(childElement.getNodeName())) {
							bean.setAge(childElement.<span style="color:#ff6600;">getFirstChild</span>()
									.getNodeValue());
						}
					}
				}
				list.add(bean);
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}

二、PULL
public static List<PersonBean> getPersonBeans() {
		List<PersonBean> list = null;
		boolean f = false;
		PersonBean bean = null;
		XmlPullParserFactory pullParserFactory;
		try {

			pullParserFactory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = pullParserFactory.newPullParser();
			parser.setInput(PullPaserHelper.class.getClassLoader()
					.getResourceAsStream("person3.xml"),"utf-8");
			int tag = parser.getEventType();
			while (tag != XmlPullParser.END_DOCUMENT) {
				switch (tag) {
				case XmlPullParser.START_DOCUMENT:
					list = new ArrayList<PersonBean>();
					break;
				case XmlPullParser.START_TAG:
					String str = parser.getName();

					if (str.equals("person")) {
						bean = new PersonBean();
						bean.setId(Integer.valueOf(parser.getAttributeValue(0)));
						f = true;
					}
					if (f&&bean!=null) {
						if ("name".equals(str)) {
							bean.setName(parser.nextText());
						}
						if ("age".equals(str)) {
							bean.setAge(parser.nextText());
						}
					}
					break;
				case XmlPullParser.END_TAG:
					String con = parser.getName();
					if (con.equals("person") && bean != null) {
						list.add(bean);
						bean = null;
						f = false;
					}

					break;

				default:
					break;
				}
				tag = parser.next();

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return list;
	}

三、SAX
public class SaxHanderHelper extends DefaultHandler {

	List<PersonBean> personBeans;
	String tag;

	public List<PersonBean> getPersonBeans() {
		return personBeans;
	}

	public SaxHanderHelper() {
		// TODO Auto-generated constructor stub
		personBeans = new ArrayList<PersonBean>();
	}

	PersonBean bean;

	@Override
	public void startElement(String uri,String localName,String qName,//在这里获取标签标签属性
			Attributes attributes) throws SAXException {
		// TODO Auto-generated method stub
		if (localName.equals("person")) {
			bean = new PersonBean();
			for (int i = 0; i < attributes.getLength(); i++) {
				bean.setId(Integer.valueOf(attributes.getValue(i)));
			}
		}
		tag = localName;
	}

	@Override
	public void endElement(String uri,String qName)
			throws SAXException {
		// TODO Auto-generated method stub
		if (localName.equals("person") && bean != null) {
			personBeans.add(bean);
			bean = null;
		}
		tag = null;
	}

	@Override
	public void characters(char[] ch,int start,int length)//在这里获取标签的值
			throws SAXException {
		// TODO Auto-generated method stub
		String content = new String(ch,start,length).trim();
		if (tag != null) {
			if (tag.equals("age")) {
				bean.setAge(content);
			}
			if (tag.equals("name")) {
				bean.setName(content);
			}
		}

	}

}

调用方法

			SAXParser saxParser = factory.newSAXParser();
			SaxHanderHelper handerHelper = new SaxHanderHelper();
			saxParser.parse(getInputStream(),handerHelper);
			List<PersonBean> beans = handerHelper.getPersonBeans();
原文链接:https://www.f2er.com/xml/297482.html

猜你在找的XML相关文章