JAVA解析XML与JSON

自己备份代码

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class ReadFromXMLAndJSON {
	/**
	 * 获得xml字符串中指定节点的内容
	 * @param element 	输入:Element对象
	 * @param eleName 	输入:节点名称
	 * @param list 		输出:所有满足条件的节点内容
	 */
	@SuppressWarnings("unchecked")
	public void getURLFromXml(Element element, String eleName, List<String> list) {
		for (Iterator its = element.elementIterator(); its.hasNext();) {
			Element ele = (Element) its.next();
			if (ele.getName().equals(eleName)) {
				list.add(ele.getTextTrim());
			}
			if (ele.elements().size() > 0) {
				getURLFromXml(ele, eleName, list);
			}
		}
	}

	/**
	 * 获得json字符串中指定name对应的value值
	 * @param jb	输入:JSONObject对象
	 * @param name	输入:指定name值
	 * @param list 	输出:存放指定name对应的所有value
	 */
	@SuppressWarnings("unchecked")
	public void getURLFromJson(JSONObject jb, String name, List<String> list) {
		Iterator iter = jb.keySet().iterator();
		while (iter.hasNext()) {
			String key = iter.next().toString();
			System.out.println("key=" + key + ", val=" + jb.get(key));
			if (key.trim().equals(name)) {
				list.add(jb.get(key).toString());
			}
			if (jb.get(key).toString().indexOf("{") >= 0) { // 递归调用判断条件
				JSONObject jbInner;
				if (jb.get(key).getClass().equals(JSONArray.class)) {
					for (int i = 0; i < jb.getJSONArray(key).size(); i++) {
						jbInner = JSONObject.fromObject(jb.getJSONArray(key).get(i));
						getURLFromJson(jbInner, name, list);
					}
				} else {
					jbInner = JSONObject.fromObject(jb.get(key));
					getURLFromJson(jbInner, name, list);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	public void test(String formatStr) {
		String messageXMLStr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><request_message><message>"
								+ " <title>面 包</title><title>2.20</title>"
								+ "<valid_datetime>2012-05-20 20:30:00</valid_datetime"
								+ "</message></request_message>";
		String messageJSONStr = "{ 'programmers': [{ 'firstName': 'Elliotte', 'lastName':'Harold','email': '[email protected]' },{ 'firstName3333': 'Isaac3333'}], "
								+ "'authors': [{ 'firstName': 'Isaac', 'lastName': 'Asimov', 'genre': 'science fiction' }]}";

		// 解析XML文件
		List<String> list = new ArrayList<String>();
		if (formatStr.equals("xml")) {
			try {
				Document document = DocumentHelper.parseText(messageXMLStr);
				Element root = document.getRootElement();
				getURLFromXml(root, "title", list);
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		} else if (formatStr.equals("json")) {
			JSONObject jb = JSONObject.fromObject(messageJSONStr);
			getURLFromJson(jb, "firstName", list);
		}
		for (Iterator ite = list.iterator(); ite.hasNext();) {
			System.out.println(ite.next());
		}
	}

	public static void main(String[] args) {
		CallBackServlet cbs = new CallBackServlet();
		cbs.test("xml");
		cbs.test("json");
	}
}

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