dom4j读取xml文件的一个小例子

dom4j读取xml文件的一个小例子

准备好xml,我准备了一个(记得xml前面不能有空格)

<?xml version="1.0" encoding="UTF-8"?>
<Logs count="8" src="测软件" srcIp="192.168.40.43" srcNO ="SZRJ">
<Log code = "Operation_Log" description="软件有害成都检测" id="1" version="0.1">
<Item key="log.action" value="自动搜索"/>
<Item key="log.object.name" value="我的i7主机"/>
<Item key="log.user.type" value="防病毒攻略"/>
<Item key="log.user.dn" value="跳出色情信息"/>
<Item key="log.object.ip" value="1.1.1.1"/>
<Item key="log.detect_time" value="2021-01-21 15:43:12"/>
<Item key="log.result" value="成功阻挡她脱裙子"/>
<Item key="log.object.type" value="软件"/>
<Item key="log.user.name" value="西蜀霸王枪"/>
<Item key="log.event.level" value="warn"/>
</Log>
</Logs>
1、导包
  <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>
2、准备三个实体类(根据xml内容来定的,几个类型的标签就要几个)

Item 类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="条款")
@XmlRootElement(name="Item")
@Data
public class Item {
    @XmlAttribute(name="key",required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String key;
    @XmlAttribute(name="value",required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected  String value;
}

Log 类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="日志",propOrder = {"item"})
@XmlRootElement(name="Log")
@Data
public class Log {
    @XmlAttribute(name="code",required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String code;
    @XmlAttribute(name="version",required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String version;
    @XmlAttribute(name="id")
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String id;
    @XmlAttribute(name="description")
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String description;
    @XmlElement(name = "Item",required = true)
    protected List<Item> item;
}

Logs类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "日志主题", propOrder = {"log"})
@XmlRootElement(name = "Logs")
@Data
public class Logs {
    @XmlAttribute(name = "count", required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String count;
    @XmlAttribute(name = "src", required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String src;
    @XmlAttribute(name = "srcNO", required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String srcNO;
    @XmlAttribute(name = "srcIP", required = true)
    @XmlJavaTypeAdapter(NormalizedStringAdapter.class)
    protected String srcIP;
    @XmlElement(name = "Log", required = true)
    protected List<Log> log;
}

3、代码
控制层:

  /**
     * 导入并阅读xml文件
     */
    @PostMapping("/importAndReadXml")
    @ApiOperation(value = "导入并阅读xml文件")
    public R importAndReadXml(MultipartFile file){
        R r = iSysBugService.importAndReadXml(file);
        return r;
    }

业务层:

public R importAndReadXml(MultipartFile file) {
        try {
            File fileData = multipartFileToFile(file);
            if(null != fileData && fileData.exists()){
                SAXReader saxReader = new SAXReader();
                Document document = saxReader.read(fileData);
                String logXml = document.asXML();
                StringReader stringReader = new StringReader(logXml);
                JAXBContext jaxbContext = JAXBContext.newInstance(Logs.class);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                Logs logs = (Logs)unmarshaller.unmarshal(stringReader);
                if(null == logs){
                    log.error("日志数据格式错误!devId={},xml=\n{}",logXml);
                }
                List<Log> logList = logs.getLog();
                /**
                 * 拿到数据往下进行业务………………
                 */
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 把 MultipartFile 转为File类型
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

这个并不难,但是记录一笔,免得日后要用无处可寻,手忙脚乱

上一篇:Delphi TStringList的用法


下一篇:Redis报错:-DENIED Redis is running in protected mode because protected mode is enabled