/** * */ package com.ces.component.archive.utils; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * @author ronghui * @创建日期:2020-4-26 */ public class MyNode { //节点名 public String name = ""; //节点值 public String text = ""; //属性 public Map<String,String> attrs = new HashMap<String,String>(); //子节点 public Map<String,MyNode> nodeMap = new HashMap<String,MyNode>(); //节点集合 public List<MyNode> nodeList = new ArrayList<MyNode>(); /** * 获取属性值 * @param: * @author: 戎辉 * @Time: 2020-4-26 下午4:03:47 */ public String getAttr(String name){ return attrs.get(name); } /** * 根据子节点名获取子节点 * @param: * @author: 戎辉 * @Time: 2020-4-26 下午4:03:47 */ public MyNode getNode(String name){ return nodeMap.get(name); } /** * 根据下标获取子节点 * @param: * @author: 戎辉 * @Time: 2020-4-26 下午4:03:47 */ public MyNode get(int i){ return nodeList.get(i); } /** * 获取子节点值 * @param: * @author: 戎辉 * @Time: 2020-4-26 下午4:34:09 */ public String getString(String name){ final MyNode myNode = nodeMap.get(name); if(myNode != null){ return myNode.toString(); }else{ return ""; } } public String toString(){ return this.text; } /** * 读取XML文件 * @param: * @author: 戎辉 * @Time: 2020-4-26 下午4:10:06 */ public static MyNode readerXml(String xmlPath){ return readerXml(new File(xmlPath)); } /** * 读取XML文件 * @param: * @author: 戎辉 * @Time: 2020-4-26 下午4:10:06 */ public static MyNode readerXml(File xml){ // 创建的对象reader SAXReader reader = new SAXReader(); // 通过reader对象的read方法加载xml文件,获取document对象 Document document = null; try { document = reader.read(xml); } catch (DocumentException e) { e.printStackTrace(); } MyNode node = new MyNode(); if(document!=null){ // 通过document对象获取根节点 Element root = document.getRootElement(); xmlElementIterator(root,node); } return node; } private static void xmlElementIterator(Element element,MyNode myNode){ myNode.name = element.getName(); myNode.text = element.getText(); //处理属性 @SuppressWarnings("unchecked") final List<Attribute> attributes = element.attributes(); for(Attribute attribute:attributes){ myNode.attrs.put(attribute.getName(), attribute.getValue()); } //处理子节点 @SuppressWarnings("unchecked") final List<Element> elements = element.elements(); for(Element subElement:elements){ MyNode node = new MyNode(); xmlElementIterator(subElement,node); myNode.nodeMap.put(node.name, node); myNode.nodeList.add(node); } } }
final MyNode root = MyNode.readerXml(xml);