java解析xml 工具类
解析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> loadXml(String filePath) throws Exception {
return loadXml(new FileInputStream(filePath));
}
/**
* 初始化 InputStream 指定的 XML 输入流
*
* @param in
* @return
* @throws Exception
*/
public static Map> loadXml(InputStream in) throws Exception {
Map> configMap = new HashMap>();
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 itemMap = null;
if (configMap.containsKey(idValue)) { // 如果已经存在 Map
itemMap = configMap.get(idValue);
} else { // 如果不存在就新建
itemMap = new HashMap();
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;
}
}