解析xml 工具 做个笔记
- import java.io.FileInputStream;
- import java.io.InputStream;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import org.apache.log4j.Logger;
- import org.jdom.Attribute;
- import org.jdom.Document;
- import org.jdom.Element;
- import org.jdom.input.SAXBuilder;
- public class XmlUtil {
- private static Logger log = Logger.getLogger(XmlUtil.class);
- public final static String DEFAULT_ID_KEY = "defalut";
- public final static String ID = "id";
- /**
- * 初始化 filePath 指定的 XML 文件
- *
- * @param filePath
- * @return
- * @throws Exception
- */
- public static Map<String,Map<String,String>> loadXml(String filePath) throws Exception {
- return loadXml(new FileInputStream(filePath));
- }
- /**
- * 初始化 InputStream 指定的 XML 输入流
- *
- * @param in
- * @return
- * @throws Exception
- */
- public static Map<String,Map<String,String>> loadXml(InputStream in) throws Exception {
- Map<String,Map<String,String>> configMap = new HashMap<String,Map<String,String>>();
- try {
- SAXBuilder sb = new SAXBuilder();
- Document doc = sb.build(in);
- Element root = doc.getRootElement();
- List rootList = root.getChildren();
- for (int i = 0; i < rootList.size(); i++) {
- Element rootEle = (Element) rootList.get(i);
- List childList = rootEle.getChildren();
- if (childList != null && childList.size() > 0) {
- Attribute attribute = rootEle.getAttribute(ID);
- String idValue = null;
- if (attribute == null) {
- idValue = DEFAULT_ID_KEY;
- } else {
- idValue = attribute.getValue();
- }
- if (idValue == null || "".equals(idValue)) {
- idValue = DEFAULT_ID_KEY;
- }
- Map<String,String> itemMap = null;
- if (configMap.containsKey(idValue)) { // 如果已经存在 Map
- itemMap = configMap.get(idValue);
- } else { // 如果不存在就新建
- itemMap = new HashMap<String,String>();
- configMap.put(idValue, itemMap);
- }
- for (int j = 0; j < childList.size(); j++) {
- Element childEle = (Element) childList.get(j);
- Attribute childAttribute = childEle.getAttribute(ID);
- String idKey = null;
- if (childAttribute == null) {
- idKey = DEFAULT_ID_KEY;
- } else {
- idKey = childAttribute.getValue();
- }
- itemMap.put(idKey, childEle.getText());
- }
- }
- }
- log.info("初始化 XML 配置文件成功");
- } catch (Exception ex) {
- log.error("初始化 XML 配置文件失败,原因:" + ex);
- throw ex;
- }
- return configMap;
- }
- }