JDOM 封装XML操作

package org.jdom;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.xpath.XPath;

import thtf.ebuilder.Config;

/**
 * XML简化操作类
 * 
 * @author kettas 3:11:54 PM
 */
public class XML {
	private static Document document = null;
	/**
	 * 是否存在此文件 <br>
	 * 如果不存在就抛出异常,存在就返回此文件
	 * 
	 * @param file 文件对象
	 * @return File
	 * @throws IOException
	 */
	protected static File readFile(File file) throws IOException {
		try {
			if (file.exists()) {
				return file;
			}
		} catch (Exception e) {
			throw new IOException("找不到文件" + e.getMessage());
		}
		throw new IOException("找不到文件");
	}
	
	/**
	 * <pre>
	 * 将文件转换为Document对象
	 * <code>Document doc=XML.fileToDocument(new File("c://abc/a.xml"));</code>
	 * </pre>
	 * @param file 文件路径
	 * @return Document
	 * @throws JDOMException
	 */
	public static Document fileToDocument(File file) throws JDOMException {
		try {
			document = new SAXBuilder(false).build(readFile(file));
			return document;
		} catch (IOException e) {
			document=null;
			e.printStackTrace();
			throw new JDOMException("Can't find ["+file.getPath()+"]file !");
		}catch (Exception e) {
			document=null;
			throw new JDOMException(e.getMessage());
		}
	}

	/**
	 * <pre>自定义表达式的方式来读取配置文件信息:并指定你需要操作的文件的路径
	 * <code>List list=XML.fileToDocument(new File("c://abc/a.xml"));</code></pre>
	 * @param file xml 文件路径
	 * @param express xpath查询表达式
	 * @return List&lt;Element>
	 * @throws JDOMException
	 */
	public static List queryToElementList(File file, String express)
			throws JDOMException {
		return queryToElementList(file, XPath.newInstance(express));
	}
	/**
	 * 根据您的设置的Xpath语法查询XML文件并返回查询结果
	 * <pre>
	 * File file=new File("c:\\rss.xml");
	 * List list=XML.queryToElementList(file,XPath.newInstance("/rss/channel/title"));
	 * for(Element e:list){
	 *  System.out.println("名称:"+e.getText());
	 * }
	 * </pre>
	 * @param file
	 * @param xPath
	 * @return List
	 * @throws JDOMException
	 */
	public static List queryToElementList(File file, XPath xPath)
			throws JDOMException {
		return xPath.selectNodes(fileToElement(file));
	}
	/**
	 * 根据您的设置的Xpath语法查询Document并返回查询结果
	 * <pre>
	 * Document doc=XML.fileToDocument(new File("c:/xml.xml"));
	 * List list=org.jdom.XML.queryToElementList(doc,"/rss/channel/title");
	 * for(Element e:list){
	 *  System.out.println("名称:"+e.getText());
	 * }
	 * </pre>
	 * @param doc
	 * @param express
	 * @return List
	 * @throws JDOMException
	 */
	public static List queryToElementList(Document doc, String express)
		throws JDOMException {
		return XPath.newInstance(express).selectNodes(doc);
	}
	/**
	 * 查询文件顶层节点.
	 * @param file 文件路径
	 * @return Element
	 * @throws JDOMException
	 */
	public static Element fileToElement(File file) throws JDOMException{
		return fileToDocument(file).getRootElement();
	}
	/**
	 * 查询文件所有节点.
	 * @param file
	 * @return List
	 * @throws JDOMException
	 */
	public static List fileToElementList(File file)
			throws JDOMException {
		return fileToElement(file).getChildren();
	}
	/**
	 * 自定义Xpath查询表达式,查询指定的文件并简单封装为List of Map,并返回.
	 * @deprecated
	 * @param file 需要查询的文件路径
	 * @param express xpath查询表达式
	 * @return List
	 * @throws JDOMException
	 */
	public static List<Map<String, String>> queryToMapList(File file,
			String express) throws JDOMException {
		return elementToMap(queryToElementList(file, express));
	}
	/**
	 * 自定义Xpath查询表达式,查询指定的文件并简单封装为List of Map,并返回.
	 * @deprecated
	 * @param file 需要查询的文件路径
	 * @param express xpath查询表达式
	 * @return List
	 * @throws JDOMException
	 */
	public static List<Map<String, String>> queryAttributeToMapList(File file,
			String express) throws JDOMException {
		return elementAttributeToMap(true,queryToElementList(file, express));
	}
	/**
	 * 将节点封装成为List of Map.不推荐使用.(不支持节点属性,只支持节点)
	 * @deprecated
	 * @param elementList
	 * @return List
	 */
	public static List<Map<String, String>> elementToMap(
			List elementList) {
		return elementAttributeToMap(false,elementList);
	}
	private static Map toMap(boolean readAttribute,Element element){
		int j=0;
		Map<String, String> map = new HashMap<String, String>();
		//读取所有属性
		List<Attribute> as=element.getAttributes();
		for (j=0;readAttribute&&as!=null&&j<as.size();j++) {
			Attribute _as=as.get(j);
			map.put(_as.getName(), element.getAttributeValue(_as.getName()));
		}
		//读取所有子节点
		List listElement = element.getChildren();
		for (j=0;listElement!=null&&j<listElement.size();j++) {
			Element element2=(Element)listElement.get(j);
			map.put(element2.getName(), element2.getText());
		}
		return map;
	}
	public static List<Map<String, String>> elementAttributeToMap(boolean readAttribute,
			List elementList) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (int i=0,j=0;list!=null&&i<elementList.size();i++) {
			Element element=(Element)elementList.get(i);
			list.add(toMap(readAttribute,element));
		}
		return list;
	}
	/**
	 * 将Document对象保存为一个xml文件
	 * <pre>
	 * Document doc=new Document();
	 * Element e=new Element("r");
	 * doc.setRootDocument(e);
	 * XML.documentToFile(doc,new File("c://abc/a.xml"));</pre>
	 * @param document 对象 
	 * @param saveFile  文件保存地址
	 * @return boolean
	 */
	public static boolean documentToFile(Document document, File saveFile) {
		try {
			if(!saveFile.getParentFile().exists()){
				FileUtils.forceMkdir(saveFile.getParentFile());
			}
			FileOutputStream out1 = new FileOutputStream(saveFile);
			Format format = Format.getPrettyFormat();
			format.setEncoding(Config.DEFAULT_TYPE);
			format.setIndent("\t");
			XMLOutputter outputter = new XMLOutputter(format);
			outputter.output(document, out1);
			out1.flush();
			out1.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;

	}
	/**
	 * 将表达式查出的节点全部删除,并保存。
	 * <pre>
	 * XML.remove(new File("c://abc/a.xml"),"/xml");</pre>
	 * </pre>
	 * @param file XML文件路径
	 * @param express Xpath查询表达式
	 * @return boolean
	 * @throws JDOMException
	 */
	public static boolean remove(File file, String express)
			throws JDOMException {
		List eList = queryToElementList(file, express);
		for (int i=0;eList!=null&&i<eList.size();i++) {
			Element element =(Element)eList.get(i);
			element.removeContent();
		}
		return documentToFile(document, file);
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
dom4j,jsoup,jdom,w3cdom,xstream使用代码工程 package ivyy.taobao.com.dom4j; import ivyy.taobao.com.entity.Address; import ivyy.taobao.com.entity.Location; import ivyy.taobao.com.entity.Point; import ivyy.taobao.com.entity.Pois; import ivyy.taobao.com.utils.IoUtils; import ivyy.taobao.com.utils.UrlUtils; import ivyy.taobao.com.utils.Dom4jUtils; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.jsoup.Jsoup; import org.jsoup.select.Elements; /** *@Date:2015-1-6 *@Author:liangjilong *@Email:jilongliang@sina.com *@Version:1.0 *@Description: */ @SuppressWarnings("all") public class Dom4jTest2 { public static void main(String[] args)throws Exception { //String filepath="D:/"+System.currentTimeMillis()+".xml"; String filepath="D:/test/map1.xml"; File f=new File(filepath); if(!f.exists()){ f.createNewFile(); } //List<Pois> list=getReaderXml("URL"); List<Pois> list=getReaderXml("FILE"); org.dom4j.Document doc=createAsXML(list); IoUtils.write(doc.asXML(),filepath); //格式化 Dom4jUtils.formatAsXml(doc); } /**** * 组装成一个xml * @param list * @return * @throws Exception */ private static org.dom4j.Document createAsXML(List<Pois> list) throws Exception{ org.dom4j.Document doc=DocumentHelper.createDocument(); Element root=doc.addElement("GeocoderSearchResponse");//根 root.addElement("status").setText("0");//status for (Iterator iterator = list.iterator(); iterator.hasNext();) { Pois pois = (Pois) iterator.next(); Element result=root.addElement("result");//result List<Location> listLoc=pois.getLocations(); Element location=result.addElement("location");//location for (Iterator iterator2 = listLoc.iterator(); iterator2.hasNext();) { Location locObj = (Location) iterator2.next(); location.addElement("lat").setText(locObj.getLat()+"");//lat location.addElement("lng").setText(locObj.getLng()+"");//lat result.addElement("formatted_address").setText(locObj.getFormattedAddress()+"");//formatted_address result.addElement("business").setText(locObj.getBusiness()+"");//business } List<Address> listAdd=pois.getAddress(); Element comp=result.addElement("addressComponent");//addressComponent for (Iterator iterator3 = listAdd.iterator(); iterator3.hasNext();) { Address address = (Address) iterator3.next(); comp.addElement("streetNumber").setText(address.getStreetNumber()+"");//streetNumber comp.addElement("street").setText(address.getStreet()+"");//street comp.addElement("district").setText(address.getDistrict()+"");//district comp.addElement("city").setText(address.getCity()+"");//city comp.addElement("province").setText(address.getProvince()+"");//province comp.addElement("cityCode").setText(address.getCityCode()+"");//cityCode } Element poi=result.addElement("pois").addElement("poi"); poi.addElement("addr").setText(pois.getAddr());//addr poi.addElement("distance").setText(pois.getDistance());//distance poi.addElement("name").setText(pois.getName());//name poi.addElement("poiType").setText(pois.getPoiType());//poiType poi.addElement("tel").setText(pois.getTel());//tel poi.addElement("zip").setText(pois.getZip());//zip List<Point> listPoint=pois.getPoints(); Element point=poi.addElement("point"); for (Iterator iterator4 = listPoint.iterator(); iterator4.hasNext();) { Point p = (Point) iterator4.next(); point.addElement("x").setText(p.getX()+""); point.addElement("y").setText(p.getY()+""); } } return doc; } /** * Dom4j(SAX)读取xml数据(解析) * @param params * @throws Exception */ private static List<Pois> getReaderXml(String flg) throws Exception{ String fromRead=Dom4jTest2.class.getClassLoader().getResource("xml/map1.xml").getPath(); List<Pois> list=new ArrayList<Pois>(); SAXReader saxReader = new SAXReader(); org.dom4j.Document document=null; //从api上面解析 if(flg.equals("URL")){ String url = UrlUtils.getBaiduMapUrl("你的key", "39.983424,116.322987", "xml"); document = saxReader.read(url); //从文件上面的xml解析 }else if(flg.equals("FILE")){ document = saxReader.read(new File(fromRead)); } Element resultEl = (Element)document.getRootElement().element("result"); Element poisEl=resultEl.element("pois");//pois节点 Element locationEl=resultEl.element("location");//location节点 Element addressEl=resultEl.element("addressComponent");//addressComponent节点 /*******从pois节点下面遍历多个poi节点*******/ for (Iterator<Element> poIter = poisEl.elementIterator("poi"); poIter.hasNext();) { Element element = (Element) poIter.next(); String addr = element.elementText("addr"); String distance = element.elementText("distance"); String name = element.elementText("name"); String poiType = element.elementText("poiType"); String tel =(element.elementText("tel")==""?"":element.elementText("tel")); String zip =(element.elementText("zip")==""?"":element.elementText("zip")); Pois poi=new Pois(); poi.setAddr(addr); poi.setDistance(distance); poi.setName(name); poi.setPoiType(poiType); poi.setTel(tel); poi.setZip(zip); List<Location> listLoc=new ArrayList<Location>(); /************Location***************************/ String business=resultEl.elementText("business"); String formatted_address=resultEl.elementText("formatted_address"); String lat = locationEl.elementText("lat"); String lng = locationEl.elementText("lng"); Location location=new Location(); location.setBusiness(business); location.setFormattedAddress(formatted_address); location.setLat(lat); location.setLng(lng); listLoc.add(location); poi.setLocations(listLoc); List<Address> listAddr=new ArrayList<Address>(); /************Address***************************/ Address address=new Address(); String streetNumber=(addressEl.elementText("streetNumber")==""?"":addressEl.elementText("streetNumber")); String street=(addressEl.elementText("street")==""?"":addressEl.elementText("street")); String district=(addressEl.elementText("district")==""?"":addressEl.elementText("district")); String city=(addressEl.elementText("city")==""?"":addressEl.elementText("city")); String province=(addressEl.elementText("province")==""?"":addressEl.elementText("province")); String direction=(addressEl.elementText("direction")==""?"":addressEl.elementText("direction")); String distancez=(addressEl.elementText("distance")==""?"":addressEl.elementText("distance")); address.setStreetNumber(streetNumber); address.setStreet(street); address.setCity(city); address.setDistrict(district); address.setDirection(direction); address.setDistance(distancez); address.setProvince(province); listAddr.add(address); poi.setAddress(listAddr); list.add(poi); } return list; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值