欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java组装xml和解析xml(jdom使用)

程序员文章站 2022-05-30 09:49:11
...

场景:将一张表一条记录数据组装成标准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