当前位置: 首页 > 工具软件 > dom4j > 使用案例 >

DOM4J 的使用

司寇研
2023-12-01

DOM4J的使用

vscode导包配置pom.xml

  • 本地
    <dependency>
      <groupId>dom4j</groupId>
      <artifactId>dom4j</artifactId>
      <version>2.1.1</version>
      <scope>system</scope>
      <systemPath>${project.basedir}/lib/dom4j-2.1.1.jar</systemPath>
    </dependency>

Maven

<!-- https://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
    <groupId>dom4j</groupId>
    <artifactId>dom4j</artifactId>
    <version>1.6.1</version>
</dependency>

生成XML

package com.xxx.xml.dom4j;

import java.io.File;

import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

/**
 * DOM4JWriter
 */
public class DOM4JWriter {

    public static void main(String[] args) throws IOException {
        // 输出文件路径
        String oPath = "xmlparsing/out/dom4j.xml";
        Document doc = DocumentHelper.createDocument();
        // 根节点
        Element addresslist = doc.addElement("addresslsit");
        // 创建元素节点并设置关系
        Element contacts = addresslist.addElement("contacts");
        Element name = contacts.addElement("name");
        Element email = contacts.addElement("email");
        // 设置元素内容
        name.setText("张三");
        email.setText("zs@11.com");
        // 格式化
        OutputFormat oFormat = OutputFormat.createPrettyPrint();
        oFormat.setEncoding("UTF-8");
        // 输出
        XMLWriter writer = new XMLWriter(new FileOutputStream(new File(oPath)), oFormat);
        writer.write(doc);
        System.out.println("end");
    }
}

生成的XML文件

<?xml version="1.0" encoding="UTF-8"?>
<addresslsit>
  <contacts>
    <name>张san</name>
    <email>zs@11.com</email>
  </contacts>
</addresslsit>

读取XML

package com.xxx.xml.dom4j;

import java.io.File;
import java.util.Iterator;

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

/**
 * DOM4JReader
 */
public class DOM4JReader {

    public static void main(String[] args) throws DocumentException {
        String filepath = "xmlparsing/out/dom4j.xml";
        // 建立SAXReader
        SAXReader reader = new SAXReader();
        // 读取文档对象
        Document doc = reader.read(new File(filepath));
        // 取得根节点
        Element root = doc.getRootElement();
        // 取得所有子节点
        Iterator iterator = root.elementIterator();
        while (iterator.hasNext()) {
            Element e = (Element) iterator.next();
            // 根据元素名称打印内容
            System.out.println(e.elementText("name"));
            System.out.println(e.elementText("email"));
        }
    }
}
 类似资料: