[J2EE>>Jar>>Dom4j] Dom4j解析XML

    /**
     * 读取XML文件为document<br>
     * @param path 文件路径
     * @return
     * @throws Exception 
     */
    public static Document read(String path) throws Exception{
        SAXReader reader = new SAXReader();
        File file = new File (path);
        Document doc = null;
        doc = reader.read(file); 
        return doc;
    }
    
    /**
     * 
     * 读取XML文件为document<br>
     * @param in 输入流
     * @return
     * @throws Exception
     * @author:珞珈搬砖工
     * @date:last updated time 2016年9月1日
     */
    public static Document read(InputStream in) throws Exception{
        SAXReader reader = new SAXReader();
        Document doc = null;
        doc = reader.read(in);
        return doc;
    }
    
    /**
     * 解析XML文件为document<br>
     * @param xml
     * @return
     * @throws Exception 
     */
    public static Document parse(String xml) throws Exception{
        Document doc = null;
        doc = DocumentHelper.parseText(xml);
        return doc;
    }
    
    /**
     * 查找节点List<br>
     * @param doc:文件
     * @param xpath:xpath路径
     * @return
     */
    public static List findNodes(Document doc,String xpath){
        List list = new ArrayList();
        if(doc != null)
            list = doc.selectNodes(xpath);
        return list;
    }
    /**
     * 查找节点<br>
     * @param doc:文件
     * @param xpath:xpath路径
     * @return
     */
    public static Node findNode(Document  doc,String xpath){
        Node node = null;
        if(doc != null)
            node = doc.selectSingleNode(xpath);
        return node;
    }
    

 

 

<dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <!-- 用于XPath -->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>

 

 

 

public static Map<String,String> loadXML(String _xml,String _xpath,Class<?> actionClazz){
        Map<String,String> map = new HashMap<String,String>();
        try{
            InputStream in = Thread.currentThread()
                        .getContextClassLoader().getResourceAsStream(_xml);
            Document doc = FileXml.read(in);
            String xpath = String.format(_xpath, actionClazz.getName());
            List<Node> list = FileXml.findNodes(doc, xpath);
            for(Node node:list){
                if(node instanceof Element){
                    Element element = (Element) node;
                    String text = element.getText().replaceAll("\\s", " ");
                    map.put(element.attributeValue("id"), text);
                }
                
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        return map;
    }

 

posted @ 2016-11-23 19:27  珞珈搬砖工  阅读(95)  评论(0)    收藏  举报