java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > 使用dom4j解析xml文件

使用dom4j解析xml文件问题

作者:C币贫困户

这篇文章主要介绍了使用dom4j解析xml文件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

使用dom4j解析xml文件

Stu.java

    private String name;
    private int age;
    private String sex;
    public Stu(String name, int age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
    public Stu() {
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    @Override
    public String toString() {
        return "Stu{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

student.xml

<?xml version="1.0" encoding="utf-8"?>
<students>
    <student>
        <name>张三</name>
        <age>18</age>
        <sex>男</sex>
    </student>
    <student>
        <name>李四</name>
        <age>19</age>
        <sex>女</sex>
    </student>
</students>

getxml.java

import Bean.Stu;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.util.List;
public class getxml {
    @Test
    public void get() throws Exception {
        //获取SAXReader对象
        SAXReader saxReader = new SAXReader();
        //读取配置文件
        Document read = saxReader.read("./src/main/java/src/student.xml");
        //获取根标签
        Element rootElement = read.getRootElement();
        //根据根标签获取”student“标签列表
        List<Element> students = rootElement.elements("student");
        //遍历
        for (Element student : students){
            //获取标签的文本
            String name = student.elementText("name");
            int age = Integer.parseInt(student.elementText("age"));
            String sex = student.elementText("sex");
            Stu stu = new Stu(name, age, sex);
            System.out.println(stu);
        }
    }
}

结果:

使用DOM4J解析XML文档,输出所有学员信息和添加学生信息

使用DOM4J要导包

xml信息

<?xml version="1.0" encoding="UTF-8"?>
<students> 
  <student> 
    <name>苏鸿</name>  
    <age>20</age>  
    <school>北方交大</school> 
  </student>  
  <student> 
    <name>李明</name>  
    <age>21</age>  
    <school>北大</school> 
  </student>
</students>

学生对象

package web9_29.lx.lx2;
public class Student {
    private String name;
    private int age;
    private String school;
    public Student() {
    }
    public Student(String name, int age, String school) {
        this.name = name;
        this.age = age;
        this.school = school;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    public String toString() {
        return "Student{name = " + name + ", age = " + age + ", school = " + school + "}";
    }
}

DOM4J解析XML 

1.读取XML文件,获得document对象

SAXReader saxReader=new SAXReader();
Document doc=saxReader.read(new File("input.xml"));//input是你xml的文件位置

2.//获取文档的根元素Element root=doc.getRootElement();

3.//获取某接节点的单个子节点

Element  nameElement=root.element("name");//name是节点名

4.//获取节点的文本内容

String text=nameElement.getText();
package web9_29.lx.lx2;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DOM4JStu {
    public static void main(String[] args) {
        //创建list集合保存学生对象
        List<Student> list=new ArrayList<>();
        try {
            //读取XML文件,获得document对象
            SAXReader saxReader=new SAXReader();
            Document doc=saxReader.read(new File("src\\web9_29\\lx\\lx2\\Student.xml"));
            //获取文档的根元素
            Element root=doc.getRootElement();
            //遍历根元素的节点元素
            Iterator<?> it=root.elementIterator();
            while (it.hasNext()){
                //创建学生对象
                Student student = new Student();
                Element stuElement = (Element) it.next();
                //获取节点
                Element nameElement=stuElement.element("name");
                Element ageElement=stuElement.element("age");
                Element schoolElement=stuElement.element("school");
                //获取节点的文本类容给学生对象
                student.setName(nameElement.getText());
                student.setAge(Integer.parseInt(ageElement.getText()));
                student.setSchool(schoolElement.getText());
                //将学生对象添加到list集合中
                list.add(student);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //遍历集合
        for (Student s : list) {
            System.out.println(s);
        }
    }
}
 

运行图片

 

添加学员信息

package web9_29.lx.lx2;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DOM4JStuAdd {
    public static void main(String[] args) {
        //创建集合存储学生对象
        List<Student> list=new ArrayList<>();
        //要添加的学生信息
        list.add(new Student("赵六",20,"安徽大学"));
        list.add(new Student("刘启",21,"安徽大学江淮学员"));
        try {
            //读取XML文件,获得document对象
            SAXReader saxReader = new SAXReader();
            Document document=saxReader.read(new File("src\\web9_29\\lx\\lx2\\Student.xml"));
            //获取文档的根元素
            Element root=document.getRootElement();
            for (Student s : list) {
                //添加student节点
                Element newStudentElement=root.addElement("student");
                //在student节点下添加节点name,age,school。并通过学生对象赋值
                Element nameElement=newStudentElement.addElement("name");
                nameElement.setText(s.getName());
                Element ageElement=newStudentElement.addElement("age");
                ageElement.setText(String.valueOf(s.getAge()));
                Element schoolElement=newStudentElement.addElement("school");
                schoolElement.setText(s.getSchool());
            }
            OutputFormat of=OutputFormat.createPrettyPrint();
            //指定编码格式
            of.setEncoding("UTF-8");
            XMLWriter writer=new XMLWriter(new FileWriter("src\\web9_29\\lx\\lx2\\Student.xml"),of);
            writer.write(document);
            writer.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

运行后图片

 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文