采用DOM4J解析xml,带例子。

这里主要是解析一般常用的三级,更多级数可以写死,一层一层的累加,也可以写个灵活的方法来判断级数在解析。例子适合才接触的新人。

解析的xml:

<?xml version="1.0" encoding="gbk"?>
<ROWDATA>
<ROW>
  <a>1111</a>
  <b>2222</b>
  <c>3333</c>
  <d>4444</d>
</ROW>
<ROW>
  <a>aaaa</a>
  <b>bbbb</b>
  <c>cccc</c>
  <d>dddd</d>
</ROW>
</ROWDATA>

PaseXml类:

package com.cn;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 解析三级xml
 * 
 */
public class PaseXml {
	public List<Map<String, String>> pXml(String fileName) {
		Map<String, String> map = null;
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();

		SAXReader reader = new SAXReader();
		try {
			Document document = reader.read(fileName);
			Element root = document.getRootElement();
			Iterator<?> it = root.elementIterator();
			while (it.hasNext()) {
				map = new HashMap<String, String>();
				// ROW节点
				Element e = (Element) it.next();
				Iterator<?> its = e.elementIterator();
				while (its.hasNext()) {
					Element el = (Element) its.next();
					// xml的键值放入map里面
					map.put(el.getName(), el.getText());
				}
				list.add(map);
			}
		} catch (DocumentException e1) {
			e1.printStackTrace();
		}
		return list;
	}
}

main类:

public static void main(String[] args) {
		PaseXml px = new PaseXml();
		String fileName = "D:/xmlfile/test.xml";
		// String fileName = "D:/xmlfile/HOSPITAL.xml";
		List<Map<String, String>> list = px.pXml(fileName);
		Iterator<?> it = list.iterator();
		while (it.hasNext()) {
			Map<String, String> map = (Map<String, String>) it.next();
			Iterator<?> itm = map.entrySet().iterator();
			while (itm.hasNext()) {
				Map.Entry entry = (Map.Entry) itm.next();
				Object key = entry.getKey();
				Object value = entry.getValue();
				System.out.println(key + ":" + value);
			}
			System.out.println("----------------------------------");
		}
	}

输出结果:

d:4444
b:2222
c:3333
a:1111
----------------------------------
d:dddd
b:bbbb
c:cccc
a:aaaa
----------------------------------



你可能感兴趣的:(xml,String,object,list,Class,encoding)