欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

XML DOM解析XML文件

程序员文章站 2022-05-29 08:20:47
...

采用DOM解析student.xml文件,将解析的每组数据保存在Student对象中,然后将Student对象添加到List集合。

注:解析器读入整个文档,然后构建一个驻留内存的树结构,使用 DOM 接口来操作这个树结构。


一、解析的XML文件(student.xml)

<?xml version="1.0" encoding="utf-8" ?><!--xml文档声明-->
<!--DTD约束-->
<!DOCTYPE class [
        <!ELEMENT student (name,age,sex,height)>
        <!ELEMENT name (#PCDATA)>
        <!ELEMENT age (#PCDATA)>
        <!ELEMENT sex (#PCDATA)>
        <!ELEMENT height (#PCDATA)>
        ]>

<!--只能有一个根标签-->
<class>
    <!--设置属性-->
    <student id="1" user="lisi">
        <name>李四</name>
        <age>18</age>
        <sex>男</sex>
        <height>182</height>
    </student>
    <student id="2" user="wangwu">
        <name>王五</name>
        <age>19</age>
        <sex>男</sex>
        <height>172</height>
    </student>
</class>
二、解析代码

package com.xml.main;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class DOMParseMain {
    public static void main(String[] args) {
        try {
//            使用List存储解析到的学生信息
            ArrayList<Student> list = new ArrayList<>();

            //DOM解析的步骤
            //步骤一:创建DOM解析工厂
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            //步骤二:通过解析工厂 创建一个XML文档解析者
            DocumentBuilder documentBuilder = factory.newDocumentBuilder();
            //步骤三: 解析指定XML文件
            Document document = documentBuilder.parse(new File("student.xml"));
            //开始解析
            Element documentElement = document.getDocumentElement();
            //获取根元素节点下所有的节点(包含此节点的所有子节点,如:元素节点,文本节点,注释节点,空格换行等)
            NodeList childNodes = documentElement.getChildNodes();

            for (int i = 0; i < childNodes.getLength(); i++) {
                Node item = childNodes.item(i);
                Student student = new Student();
//                只获取元素节点并且节点名称为student
                if (item.getNodeType() == Node.ELEMENT_NODE && "student".equals(item.getNodeName())) {
                    NamedNodeMap attributes = item.getAttributes();//得到Student所有的属性
                    Node id = attributes.getNamedItem("id");//获取id节点
                    String idValue = id.getNodeValue();//获取id的属性值

                    Node user = attributes.getNamedItem("user");//获取user节点
                    String userValue = user.getNodeValue();//获取user 属性值

                    //添加信息到student对象中
                    student.setId(Integer.parseInt(idValue));
                    student.setUser(userValue);

                    //遍历student节点下面的子节点
                    NodeList childNodes1 = item.getChildNodes();
                    for (int j = 0; j < childNodes1.getLength(); j++) {
                        Node item1 = childNodes1.item(j);
//                        获取元素节点
                        if (item1.getNodeType() == Node.ELEMENT_NODE) {
                            switch (item1.getNodeName()) {
                                case "name":
                                    String nameValue = item1.getFirstChild().getNodeValue();
                                    student.setName(nameValue);
                                    break;
                                case "height":
                                    String heightValue = item1.getFirstChild().getNodeValue();
                                    student.setHeight(Double.parseDouble(heightValue));
                                    break;
                                case "age":
                                    String ageValue = item1.getFirstChild().getNodeValue();
                                    student.setAge(Integer.parseInt(ageValue));
                                    break;
                                case "sex":
                                    String sexValue = item1.getFirstChild().getNodeValue();
                                    student.setSex(sexValue);
                                    break;
                            }
                        }
                    }
                    list.add(student);
                }
            }
//遍历List
            for (Student s : list) {
                System.out.println(s.toString());
            }

        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
}


 三、Student.java

package com.xml.main;

public class Student {
    private int id;
    private String user;
    private String name;
    private String sex;
    private int age;
    private double height;

    public Student() {
    }

    public Student(int id, String user, String name, String sex, int age, double height) {
        this.id = id;
        this.user = user;
        this.name = name;
        this.sex = sex;
        this.age = age;
        this.height = height;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getHeight() {
        return height;
    }

    public void setHeight(double height) {
        this.height = height;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", user='" + user + '\'' +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", age=" + age +
                ", height=" + height +
                '}';
    }
}


四、解析结果

XML DOM解析XML文件