Java解析XML和json几个小例子

一、DOM4J解析xml

案例1:解析如下xml



	张三
	
	20

代码如下:

File file = new File("d:/test/**.xml");
		// 创建流
		SAXReader reader = new SAXReader();
		// 读取XML
		Document document = reader.read(file);
		// 获取根节点
		Element rootEle = document.getRootElement();
		System.out.println("根节点:" + rootEle.getName());
		// 获取根节点下的
		String name = rootEle.elementTextTrim("name");
		String sex = rootEle.elementTextTrim("sex");
		String age = rootEle.elementTextTrim("age");
		System.out.println("name:" + name + " sex:" + sex + " age:" + age);


案例2:解析如下xml


 
    
      鬼吹灯 
      天下霸唱 
    
    
      盗墓笔记 
      南派三叔 
    

代码:

File file = new File("d:/**/book.xml");
		// 创建流
		SAXReader reader = new SAXReader();
		// 读取XML
		Document document = reader.read(file);
		// 获取根节点
		Element rootEle = document.getRootElement();
		System.out.println("根节点:" + rootEle.getName());
		// 获取根节点下的子节点book
		Iterator book = rootEle.elementIterator("book");
		// 遍历book节点
		while (book.hasNext()) {
			Element bookEle = (Element) book.next();
			// 获取book节点上的id
			String id = bookEle.attributeValue("id");
			// 获取book节点下的name
			String name = bookEle.elementTextTrim("name");
			// 获取book节点下的author
			String author = bookEle.elementTextTrim("author");
			System.out.println("id:" + id + " name:" + name + " author:"
					+ author);
		}


二、解析json

案例一:list、map集合转json

// list集合转换为json
		List list = new ArrayList();
		list.add("aaaa");
		list.add("bbbb");
		JSONArray arrlist = JSONArray.fromObject(list);
		System.out.println(arrlist);

		// map集合转换为json
		Map map = new HashMap();
		map.put("name", "张三");
		map.put("age", "22");
		map.put("sex", "男");
		map.put("address", "上海");
		JSONArray arrmap = JSONArray.fromObject(map);
		System.out.println(arrmap);

案例二:json数据转Javabean

String jsonStr = "[{\"age\": 25,\"sex\": \"female\",\"grades\": \"三班\",\"name\": \"张三\"},{\"age\": 26,\"sex\": \"male\",\"grades\": \"三班\",\"name\": \"李四\"}]";
		JSONArray json = JSONArray.fromObject(jsonStr);
		List stlist = new ArrayList();
		stlist = (List) JSONArray.toCollection(json, Students.class);
		for (Students s : stlist) {
			System.out.println(s.getName());
		}
public class Students {

	private String age;
	private String sex;
	private String name;
	private String grades;
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getGrades() {
		return grades;
	}
	public void setGrades(String grades) {
		this.grades = grades;
	}
	@Override
	public String toString() {
		return "Students [age=" + age + ", sex=" + sex + ", name=" + name
				+ ", grades=" + grades + "]";
	}
	

}
后续还会补充


你可能感兴趣的:(Java实例)