dom4j解析xml

package com.app.duapp;
import java.io.File;
import java.util.Iterator;

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

@SuppressWarnings("all")
public class Test2 {
	private static String url = "http://api.map.baidu.com/geocoder/v2/?ak=E4805d16520de693a3fe707cdc962045&callback=renderReverse&location=39.983424,116.322987&output=xml&pois=1";
	
	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		readXml(url);

	}
	public static void readXml(String url) {
		try {
			SAXReader reader = new SAXReader();
			Document document =reader.read(url);//如果是本地的xml就new File(filename);
			Element root = document.getRootElement();//获取根节点
			
			System.out.println(root.elementText("status"));//状态-->第一个大节点
			
			Iterator<Element> iter = root.elementIterator("result");//第二大节点
			for (Iterator iter1 =iter; iter1.hasNext();) {
				Element Node1=(Element)iter1.next();
				
				Element location=Node1.element("location");//location节点
				String lat=location.elementText("lat");//纬度
				String lng=location.elementText("lng");//经度
				System.out.println(lat);
				System.out.println(lng);
				
				String format_addr=Node1.elementText("formatted_address");
				System.out.println(format_addr);
				String business=Node1.elementText("business");
				System.out.println(business);
				
				
				Element addressComponent=Node1.element("addressComponent");//addressComponent节点
				if(addressComponent.elementText("streetNumber")!=""&&addressComponent.elementText("streetNumber")!=null)
				{
					System.out.println(addressComponent.elementText("streetNumber"));
				}
				System.out.println(addressComponent.elementText("street"));
				System.out.println(addressComponent.elementText("district"));
				System.out.println(addressComponent.elementText("city"));
				System.out.println(addressComponent.elementText("province"));
				
			    String  cityCode=Node1.elementText("cityCode");//cityCode节点
			    System.out.println(cityCode);
			    
			    Element poisNode=Node1.element("pois");//pois节点
			    
			    for (Iterator iter2 = poisNode.elementIterator(); iter2.hasNext();) {
					Element poiNode=(Element)iter2.next();
					System.out.println("addr="+poiNode.elementText("addr"));
					System.out.println("distance="+poiNode.elementText("distance"));
					System.out.println("name="+poiNode.elementText("name"));
					System.out.println("tel="+poiNode.elementText("tel"));
					if(poiNode.elementText("zip")!=""&&poiNode.elementText("zip")!=null)
			        {
						System.out.println("zip="+poiNode.elementText("zip"));
					}
					Element point=poiNode.element("point");
					System.out.println("x="+point.elementText("x"));
					System.out.println("y="+point.elementText("y"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

你可能感兴趣的:(xml,dom4j)