dom4j解析Xml文件工具类

来源:互联网 发布:linux 改名字命令 编辑:程序博客网 时间:2024/05/16 14:47

dom4j解析xml

public class XmlUtil {/** *  * @方法声明 读取文件 * @param filePath 文件路径 * @param encoding 读取编码格式 * @return */public static List readXmlFile(String filePath, String encoding) {try {if (encoding == null || "".equals(encoding)) {encoding = "UTF-8";}File file = new File(filePath);List list = new ArrayList<>();// 判断文件是否存在if (file.isFile() && file.exists()) { // 考虑到编码格式InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);BufferedReader bufferedReader = new BufferedReader(read);String lineText = null;String allText = "";int i = 0;while ((lineText = bufferedReader.readLine()) != null) {if (i != 0) {allText = allText + lineText;}i++;}list = XmlUtil.Xml2Map(allText);read.close();return list;} else {System.out.println("找不到指定的文件");}} catch (Exception e) {System.out.println("读取文件内容出错");e.printStackTrace();}return null;}/** *  * @方法说明  节点解析 * @param xml * @return */public static List Xml2Map(String xml) {Document doc;try {doc = DocumentHelper.parseText(xml);} catch (DocumentException e1) {e1.printStackTrace();return null;}List list = new ArrayList<>();if (doc == null)return list;Element root = doc.getRootElement();list = Dom2Map(root);return list;}/** *  * @方法声明 子节点解析(递归) * @param root * @return */@SuppressWarnings("unchecked")public static List<Map<String, Object>> Dom2Map(Element root) {List list = new ArrayList<>();//节点遍历for (Iterator<Element> iterator = root.elementIterator(); iterator.hasNext();) {Element e = (Element) iterator.next();Map<String, Object> map = new HashMap<String, Object>();String key = "";String value = "";Iterator attr = e.attributes().iterator();//节点属性遍历while (attr.hasNext()) {Attribute attribute = (Attribute) attr.next();key = attribute.getName();value = e.attribute(key).getValue();map.put(key, value);}// 判断有无子节点,有就递归解析子节点if (e.elements().size() > 0) {map.put("childnode", Dom2Map(e)); list.add(map);} else {list.add(map);}}return list;}}