dom4j is easy to use

1. You need to use the jar package of dom4j. For the convenience of opening xml, design a simple encapsulation class.

package cn.com.gtmc.glaf2.util;

import java.io.File;
import java.net.URISyntaxException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

public class XmlUtil {
    /**
     * @param path
     * Relative path, relative to the classes folder
     * @return Document
     *            org.dom4j.Document
     * @throws DocumentException
     */
    public static Document getDocument(String path) throws DocumentException, URISyntaxException {
        String filePath = XmlUtil.class.getClassLoader().getResource("").toURI().getPath() + path;

        SAXReader reader = new SAXReader();
        Document doc = reader.read(new File(filePath));
        return doc;
    }

}

2. Examples of use

<?xml version="1.0" encoding="UTF-8"?>
<workbook>
    <worksheet index="0">
        <cell src="Supplier.remark" target="B3" description="备注" />
    </worksheet>
</workbook>
        try {
            Supplier obj = (Supplier)params.get("obj");
            
            Document doc = XmlUtil.getDocument("excel\\supplier-import.xml");
            Element root = doc.getRootElement ();
            
            List nodes = root.selectNodes("worksheet/cell");
            Iterator it = nodes.iterator();
            while(it.hasNext()) {
               Element ele = (Element)it.next();
               String src = ele.attributeValue("src");
               String cellTarget = ele.attributeValue("target");
               if(src != null && !"".equals(src)) {
                   String[] splits = src.split("\\.");
                   String className = splits[0];
                   String filedName = splits[1];
                                   //。。。
               }
            }                

        } catch (Exception e) {
            LOG.error("", e);
        }

In particular, note that the above Element.selectNodes method uses XPath syntax. This function is not included in dom4j.jar. You need to add the following jar package (maven project, non-maven project needs to be downloaded by yourself), otherwise an error will be reported .

        <!-- https://mvnrepository.com/artifact/jaxen/jaxen -->
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.1.6</version>
        </dependency>

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326828997&siteId=291194637