1. 程式人生 > >java組裝xml和解析xml(jdom使用)

java組裝xml和解析xml(jdom使用)

場景:將一張表一條記錄資料組裝成標準XML,將標準XML解析放入HashMap中
1.組裝XML

        /** 組裝XML */
	public static String formatDataToXml(Map mapdData) {

		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xml.append("<DATASET>");
		xml.append("<ROW>");
		if (mapdData != null) {
			Set<?> set = mapdData.entrySet();
			Iterator<?> iterator = set.iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry) iterator.next();
				xml.append("<C N=\"" + entry.getKey() + "\">"
						+ entry.getValue() + "</C>");
			}
		}
		xml.append("</ROW>");
		xml.append("</DATASET>");
		return xml.toString();
	}

2.解析XML

        /** 解析XML */
	public static Map<String, String> parseXml(String xmlData,String attrName) {
		logger.info("入參xml:" + xmlData);
		StringReader reader= new StringReader(xmlData);
		InputSource source = new InputSource(reader);  
		SAXBuilder saxbuilder = new SAXBuilder();  
		Map<String, String> map = new HashMap<String, String>();
		try {
			Document doc = saxbuilder.build(source);  
			Element root = doc.getRootElement();  
			List<Element> children = root.getChildren(); 
			for (Element e : children) {
				List<Element> row = e.getChildren();  
				for (Element r : row) {
					map.put(r.getAttributeValue(attrName),
							r.getText() == null ? "" : r.getText().trim());
				}
			}
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
		return map;
	}

3.測試方法

        /**測試*/
	public static void main(String []args){	
		logger.info("測試開始.....");
		Map<String, Object> mapInfo = new HashMap<String, Object>();
		mapInfo.put("CITY_NAME", "廈門");
		mapInfo.put("LAND_AREA", "1699.39");
		mapInfo.put("POPULATION", "401");
		mapInfo.put("GROSS", "4351.18");
		mapInfo.put("AREA_NUMBER", "350200");
		mapInfo.put("POSTAL_CODE", "361000");
		mapInfo.put("TELEPHONE_CODE", "0592");
		mapInfo.put("CAR_CODE", "閩D");
		mapInfo.put("CITY_DESCRIBE", "適合居住的城市.");
		String rtn = formatDataToXml(mapInfo);
		Map<String, String> info = parseXml(rtn,"N");
		logger.info("解析資訊:" + info.toString());
		logger.info(rtn);
		logger.info("測試結束.....");
	}

4.建表語句

CREATE TABLE `t_city` (
  `CITY_NAME` VARCHAR(64) COLLATE utf8_bin NOT NULL COMMENT '城市名',
  `LAND_AREA` DOUBLE DEFAULT NULL COMMENT '城市面積',
  `POPULATION` BIGINT(16) DEFAULT NULL COMMENT '城市人口',
  `GROSS` DOUBLE DEFAULT NULL COMMENT '生產總值',
  `AREA_NUMBER` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '行政區劃程式碼',
  `POSTAL_CODE` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '郵政編碼',
  `TELEPHONE_CODE` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '電話區號',
  `CAR_CODE` VARCHAR(64) COLLATE utf8_bin DEFAULT NULL COMMENT '車牌程式碼',
  `CITY_DESCRIBE` VARCHAR(512) COLLATE utf8_bin DEFAULT NULL COMMENT '城市描述'
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='城市資訊表'

5.資料模板

<?xml version="1.0" encoding="UTF-8"?>
<DATASET>
  <ROW>
    <C N="CAR_CODE">閩D</C>
    <C N="AREA_NUMBER">350200</C>
    <C N="LAND_AREA">1699.39</C>
    <C N="TELEPHONE_CODE">0592</C>
    <C N="CITY_NAME">廈門</C>
    <C N="CITY_DESCRIBE">適合居住的城市.</C>
    <C N="POSTAL_CODE">361000</C>
    <C N="POPULATION">401</C>
    <C N="GROSS">4351.18</C>
  </ROW>
</DATASET>

6.jar包版本 
  jdom-2.0.6.jar
  下載地址: http://www.jdom.org/downloads/index.html
7.完整類

        public class OperateXmlUtils {

	private static Logger logger = LoggerFactory.getLogger(OperateXmlUtils.class);

	/** 組裝XML */
	public static String formatDataToXml(Map mapdData) {

		StringBuffer xml = new StringBuffer();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
		xml.append("<DATASET>");
		xml.append("<ROW>");
		if (mapdData != null) {
			Set<?> set = mapdData.entrySet();
			Iterator<?> iterator = set.iterator();
			while (iterator.hasNext()) {
				Map.Entry entry = (Map.Entry) iterator.next();
				xml.append("<C N=\"" + entry.getKey() + "\">"
						+ entry.getValue() + "</C>");
			}
		}
		xml.append("</ROW>");
		xml.append("</DATASET>");
		return xml.toString();
	}

	/** 解析XML */
	public static Map<String, String> parseXml(String xmlData,String attrName) {
		logger.info("入參xml:" + xmlData);
		StringReader reader= new StringReader(xmlData);
		InputSource source = new InputSource(reader);  
		SAXBuilder saxbuilder = new SAXBuilder();  
		Map<String, String> map = new HashMap<String, String>();
		try {
			Document doc = saxbuilder.build(source);  
			Element root = doc.getRootElement();  
			List<Element> children = root.getChildren(); 
			for (Element e : children) {
				List<Element> row = e.getChildren();  
				for (Element r : row) {
					map.put(r.getAttributeValue(attrName),
							r.getText() == null ? "" : r.getText().trim());
				}
			}
		} catch (JDOMException | IOException e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**測試*/
	public static void main(String []args){	
		logger.info("測試開始.....");
		Map<String, Object> mapInfo = new HashMap<String, Object>();
		mapInfo.put("CITY_NAME", "廈門");
		mapInfo.put("LAND_AREA", "1699.39");
		mapInfo.put("POPULATION", "401");
		mapInfo.put("GROSS", "4351.18");
		mapInfo.put("AREA_NUMBER", "350200");
		mapInfo.put("POSTAL_CODE", "361000");
		mapInfo.put("TELEPHONE_CODE", "0592");
		mapInfo.put("CAR_CODE", "閩D");
		mapInfo.put("CITY_DESCRIBE", "適合居住的城市.");
		String rtn = formatDataToXml(mapInfo);
		Map<String, String> info = parseXml(rtn,"N");
		logger.info("解析資訊:" + info.toString());
		logger.info(rtn);
		logger.info("測試結束.....");
	}
	
}


以上,TKS