Java--xml-dom4j

Posted 人塞不能怨

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java--xml-dom4j相关的知识,希望对你有一定的参考价值。

Java-xml之dom4j

使用java-dom4j操作xml格式文件

1. 建立Maven工程并添加依赖

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

2. 初始化配置

public class Dom4jDemo
	//文件路径
	final String PATH;
	//xml 文件内容字符编码
	final String CODE = “UTF-8;
	//xml dom输出流缓存大小
	final int BUFFER_SIZE = 8*1024*1024;
	//日期格式化 年-月-日
	SimpleDateFormat sdfDate;
	//时间格式化 时:分:秒
	SimpleDateFormate sdfTime;
	//时间格式话 年-月-日 时:分:秒
	SimpleDateFormate sdf;
	//xml 文档对象
	Document document;
	//xml 文档根节点元素
	Element root;
	//xml dom输出流输出格式
	OutputFormat pretty;

	public Dom4jDemo(String path)
		this.PATH = path;
		sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
		sdfDate = new SimpleDateFormat("yyyy-MM-dd");
		sdfTime = new SimpleDateFormat("HH:mm:ss");
		SAXReader sax = new SAXReader();
		document = sax.read(new File(PATH));
		root = document.getRootElement();
		pretty = OutputFormat.createPrettyPrint();
		pretty.setEncoding(CODE)
	
	
	//写盘操作
	public void write() throws IOException
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(PATH),CODE),BUFFER_SIZE);
		XMLWriter xml = new XMLWriter(bw,pretty);
		xml.writer(document);
		xml.close();
	

3. xml文件增删改查
3.1 添加节点和属性

public void add()
	Element e = root.addElement("record");
	Date date = new Date();
	e.addAttribute("date",sdfDate.format(new Date()));
	e.addAttribute("time",sdfTime.format(new Date()));
	e.addAttribute("article","ArrayList.txt");
	e.addElement("wordCount").setText("460");
	e.addElement("letterCount").setText("1111");
	e.addElement("specialSignCount").setText("88");
	e.addElement("speed").setText("205");
	e.addElement("timeConsumption").setText("66");
	e.addElement("accuracy").setText("0.98");

添加后的xml如下

<?xml version="1.0" encoding="UTF-8"?>

<records> 
  <record date="2021-04-29" time="18:19:13" article="ArrayList.txt"> 
    <wordCount>460</wordCount>  
    <letterCount>1111</letterCount>  
    <specialSignCount>88</specialSignCount>  
    <speed>205</speed>  
    <timeConsumption>66</timeConsumption>  
    <accuracy>0.98</accuracy> 
  </record>
</records>

3.2 修改节点和属性

public void modify() throw IOException
	String date = "2021-04-28";
	Node single = findSingle(date);
	if(null == single)
		System.out.println(date + "not exist");
		return;
	
	//为方便操作,将节点强转为元素
	Element e = (Element)single;
	//根据属性名获取e属性对象,并修改属性值
	e.attribute("time").setValue("00:00:00");
	e.attribute("article").setValue("Xxx.xx");
	//根据子元素名称获取e子元素对象,并修改子元素文本内容
	e.element("wordCount").setText("111");
	e.element("letterCount").setText("222");
	e.element("specialSignCount").setText("333");
	e.element("speed").setText("444");
	e.element("accuracy").setText("555");
	e.element("timeConsumption").setText("6666");
	write();
	System.out.println(succeed);

3.3 移除节点

public void remove() throws IOException
	String date = "2021-04-28";
	Node single = findSingle(date);
	if(null == single) System.out.println(date + "not exist")
	root.remove(single);
	write();
	System.out.println("succeed");

3.4 查找

//根据属性查找节点
public void findSingle(String date)
	//xml-path绝对路径
	//return document.selectSingleNode("/records/record[@date='" + date + "']");
	return document.selectSingleNode("//record[@date='" + date + "']");


//查找所有
public void findAll() throws ParseException
	List<Element> elements = root.elements();
	if(elements.size()==0)
		System.out.println("element size zero");
		return;
	
	for(Record record : toRecords(elements))
		System.out.println(record);
	


//部分内容查找
public void findSome() throws ParseException
	String article = "HashMap.txt";
	List<Element> elements = 
	//单条件查找
	//document.selectNodes("//record[@article='"' + article + "']");
	//document.selectNodes("//record[wordCount[text()='" + 460 + "']]");
	//document.selectNodes("//record[wordCount[text()<'" + 460 + "']]");
	//document.selectNode("//record[contains(@article,'.txt')]");
	document.selectNode("//record[contains(@article,concat("","Set",""))]");
	//双条件
	//document.selectNodes("//record[wordCount[text()<'" + 460 + "']][speed[text(0<'" + 200 + "']]");
	if(elements.size()==0)
		System.err.println("element size zero");
		return;
	
	List<Record> records = toRecords(elements);
	for(Record record : records)
		System.out.println(record);
	


4. 节点和java对象映射
新建实体类Record

class Record
        private Date date;
        private String article;
        private int wordCount;
        private int letterCount;
        private int specialSignNumber;
        private int speed;
        private long timeConsumption;
        private float accuracy;

        public Record(String date, String article, String wordCount, String letterCount, String specialSignNumber, String speed, String timeConsumption, String accuracy) throws ParseException 
            this.date = sdf.parse(date);
            this.article = article;
            this.wordCount = Integer.parseInt(wordCount);
            this.letterCount = Integer.parseInt(letterCount);
            this.specialSignNumber = Integer.parseInt(specialSignNumber);
            this.speed = Integer.parseInt(speed);
            this.timeConsumption = Long.parseLong(timeConsumption);
            this.accuracy = Float.parseFloat(accuracy);
        

        public Date getDate() 
            return date;
        

        public void setDate(Date date) 
            this.date = date;
        

        public String getArticle() 
            return article;
        

        public void setArticle(String article) 
            this.article = article;
        

        public int getWordCount() 
            return wordCount;
        

        public void setWordCount(int wordCount) 
            this.wordCount = wordCount;
        

        public int getLetterCount() 
            return letterCount;
        

        public void setLetterCount(int letterCount) 
            this.letterCount = letterCount;
        

        public int getSpecialSignNumber() 
            return specialSignNumber;
        

        public void setSpecialSignNumber(int specialSignNumber) 
            this.specialSignNumber = specialSignNumber;
        

        public int getSpeed() 
            return speed;
        

        public void setSpeed(int speed) 
            this.speed = speed;
        

        public long getTimeConsumption() 
            return timeConsumption;
        

        public void setTimeConsumption(long timeConsumption) 
            this.timeConsumption = timeConsumption;
        

        public float getAccuracy() 
            return accuracy;
        

        public void setAccuracy(float accuracy) 
            this.accuracy = accuracy;
        

        @Override
        public String toString() 
            return "Record" +
                    "date=" + sdf.format(date) +
                    ", article='" + article + '\\'' +
                    ", wordCount=" + wordCount +
                    ", letterCount=" + letterCount +
                    ", specialSignNumber=" + specialSignNumber +
                    ", speed=" + speed +
                    ", timeConsumption=" + timeConsumption +
                    ", accuracy=" + accuracy +
                    '';
        
    

映射方法

//把文件内所有记录映射为Record类型列表
private List<Record> toRecords(List<Element> list) throws ParseException
	List<Record> items = new ArrayList<>();
	for(Element e : list)
		items.add(toRecord(e));
	
	return items;


//Element => Record 映射
private Record toRecord(Element e) throws ParseException
	//提取属性
        String date = e.attributeValue("date");
        String time = e.attributeValue("time");
        String article = e.attributeValue("article");
        //提取子元素内容
        String wordCount = e.elementText("wordCount");
        String letterCount = e.elementText("letterCount");
        String specialSignCount = e.elementText("specialSignCount");
        String speed = e.elementText("speed");
        String timeConsumption = e.elementText("timeConsumption");
        String accuracy = e.elementText("accuracy");
        //创建记录对象
        return new Record(date+ " " + time,article,wordCount,letterCount,specialSignCount,speed,timeConsumption,accuracy);


//Record => Element 映射
private Element toElement(Record r)
		Element e = root.addElement("record");
        //添加属性并赋值
        e.addAttribute("date",sdfDate.format(r.getDate()));
        e.addAttribute("time",sdfTime.format(r.getDate()));
        e.addAttribute("article", r.getArticle());
        //添加子元素
        e.addElement("wordCount").setText(r.getWordCount()+"");
        e.addElement("letterCount").setText(r.getLetterCount()+"");
        e.addElement("specialSignCount").setText(r.getSpecialSignNumber()+"");
        e.addElement("speed").setText(r.getSpeed()+"");
        e.addElement("timeConsumption").setText(r.getTimeConsumption()+"");
        e.addElement("accuracy").setText(r.getAccuracy()+"");
        return e;



以上是关于Java--xml-dom4j的主要内容,如果未能解决你的问题,请参考以下文章

Java--xml-dom4j

log4j的详解

如何使用 ofx4j 解析格式错误的 xml (ofx)?

log4j2 和 syslog,使用 RFC5424 格式不显示日志消息的可变参数部分

Log4j 用法

Log4j---文件解析以及语法使用