Java——DOM解析XML

关于XML:基础知识
关于DTD:基础知识
常用的两种XML解析技术:

  • DOM:将整个xml文件读入内存并将xml中的标签生成一棵对象树,程序对于xml标签的操作转换为对树结构的操作,优点是增删改查比较方便,缺点是占用内存大,不适合大文档;
  • SAX:边解析边处理,占用内存少,解析速度快,但是只能读取XML文件不能进行增删改操作。
    常用的几个操作:
package com.kexin.day2;

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

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

//使用J2SE自带的xml解析器解析xml
public class Demo1 {
    Document document;

    @Before
    public void Before() throws ParserConfigurationException, SAXException, IOException {
        // 获取xml文件生成的对象树
        DocumentBuilderFactory builderfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = builderfactory.newDocumentBuilder();
        document = db.parse("src/com/kexin/day2/PRODUCT.xml");
    }

    // 递归遍历对象树(空格回车也是一个节点)
    public static void list(Node n) {
        NodeList nl = n.getChildNodes();
        System.out.println(n.getNodeName());
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            list(node);
        }
    }

    @Test
    public void test() {
        list(document);
    }

    // 获取结点属性值
    @Test
    public void test1() {
        NodeList nl = document.getElementsByTagName("PRODUCT");
        for (int i = 0; i < nl.getLength(); i++) {
            Node node = nl.item(i);
            Element e = (Element) node;
            System.out.println(e.getAttribute("name"));
        }
    }

    // 向xml文件中增加新节点
    @Test
    public void test2() throws FileNotFoundException, TransformerException {
        Element e = document.createElement("PRODUCT");
        e.setAttribute("name", "ipad");
        Element e1 = document.createElement("PRODUCE");
        e1.setTextContent("apple");
        Element e2 = document.createElement("PRICE");
        e2.setTextContent("1800");
        // 将结点添加到对象树,还有insertBefore等方法
        Node node = document.getElementsByTagName("PRODUCTS").item(0);
        e.appendChild(e1);
        e.appendChild(e2);
        node.appendChild(e);
    }

    // 更改或添加xml属性节点的值
    @Test
    public void test3() {
        Element e = (Element) document.getElementsByTagName("PRODUCT").item(0);
        e.setAttribute("name", "phone");
    }
    //删除xml中的节点
    @Test
    public void test4(){
        Node node = document.getElementsByTagName("PRODUCT").item(0);
        node.getParentNode().removeChild(node);
    }
    @After
    public void after() throws FileNotFoundException, TransformerException {
        // 将document写入xml
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();
        tf.transform(new DOMSource(document), new StreamResult(new FileOutputStream("src/com/kexin/day2/PRODUCT.xml")));
    }
}

PRODUCT.xml:

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

<PRODUCT name="手机">
    <PRODUCE>华为</PRODUCE>
    <PRICE>2000</PRICE>
</PRODUCT>
<PRODUCT name="ipad">
    <PRODUCE>apple</PRODUCE>
    <PRICE>2400</PRICE>
</PRODUCT>
<PRODUCT name="电脑">
    <PRODUCE>华硕</PRODUCE>
    <PRICE>4200</PRICE>
</PRODUCT>
</PRODUCTS>

作业:使用DOM实现对XML文件的一系列操作,模拟数据库存取改,实现学生信息录入、删除、读取

package com.kexin.day2;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class StuTask {
    private final String xml_path = "src/com/kexin/day2/stu_info.xml";
    private final String STU = "stu", EXAM = "exam", EXAMID = "examid", IDCARD = "idcard", NAME = "name",
            LOCATION = "location", GRADE = "grade";

    /*
     * 添加新用户
     */
    public void AddStu() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        Student stu = new Student();
        Scanner s1 = new Scanner(System.in);
        System.out.println("请输入学生姓名");
        stu.setName(s1.nextLine());
        System.out.println("请输入准考证号");
        stu.setExamid(s1.nextLine());
        System.out.println("请输入身份证号");
        stu.setIdcard(s1.nextLine());
        System.out.println("请输入学生地址");
        stu.setLocation(s1.nextLine());
        System.out.println("请输入学生成绩");
        stu.setGrade(s1.nextLine());
        Document document = this.GetDocument(xml_path);
        // 创建stu标签
        Element stu_node = document.createElement(STU);
        stu_node.setAttribute(IDCARD, stu.getIdcard());
        stu_node.setAttribute(EXAMID, stu.getExamid());
        // 创建stu标签内的name location grade标签
        Element stu_name_node = document.createElement(NAME);
        stu_name_node.setTextContent(stu.getName());
        Element stu_location_node = document.createElement(LOCATION);
        stu_location_node.setTextContent(stu.getLocation());
        Element stu_grade_node = document.createElement(GRADE);
        stu_grade_node.setTextContent(stu.getGrade());
        // 将子标签添加到stu标签内
        stu_node.appendChild(stu_name_node);
        stu_node.appendChild(stu_location_node);
        stu_node.appendChild(stu_grade_node);
        document.getElementsByTagName(EXAM).item(0).appendChild(stu_node);
        this.SvaeToXML(document);
    }

    /*
     * 删除用户
     */
    public void DeleteStu() throws ParserConfigurationException, SAXException, IOException, TransformerException {
        System.out.println("请输入准考证号");
        Scanner s1 = new Scanner(System.in);
        String examid = s1.nextLine();
        Document document = this.GetDocument(xml_path);
        NodeList nl = document.getElementsByTagName(STU);
        Element e;
        for(int i = 0;i<nl.getLength();i++){
            e = (Element) nl.item(i);
            if(e.getAttribute(EXAMID).equals(examid)){
                nl.item(i).getParentNode().removeChild(nl.item(i));
                break;
            }
        }
        this.SvaeToXML(document);
    }

    /*
     * 查询成绩
     */
    public void QuestStu() throws ParserConfigurationException, SAXException, IOException {
        System.out.println("请输入准考证号");
        Scanner s1 = new Scanner(System.in);
        String examid = s1.nextLine();
        Document document = this.GetDocument(xml_path);
        NodeList nl = document.getElementsByTagName(STU);
        Element e;
        for(int i = 0;i<nl.getLength();i++){
            e = (Element) nl.item(i);
            if(e.getAttribute(EXAMID).equals(examid)){
                System.out.println(e.getElementsByTagName(GRADE).item(0).getTextContent());
                break;
            }
        }
    }

    public Document GetDocument(String path) throws ParserConfigurationException, SAXException, IOException {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document document = db.parse(path);
        return document;
    }

    public static void main(String[] args)
            throws ParserConfigurationException, SAXException, IOException, TransformerException {
        int key = 0;
        StuTask st = new StuTask();
        Scanner scan = new Scanner(System.in);
        System.out.println("请选择操作:");
        while (key != 4) {
            System.out.println("1、添加新用户;2、删除用户;3、查询成绩;4、退出系统");
            key = scan.nextInt();
            switch (key) {
            case 1:
                st.AddStu();
                break;
            case 2:
                st.DeleteStu();
                break;
            case 3:
                st.QuestStu();
                break;
            default:
                key = 4;
            }
        }
    }

    /*
     * 将document输出至xml文件
     */
    public void SvaeToXML(Document document) throws TransformerException {
        TransformerFactory tff = TransformerFactory.newInstance();
        Transformer tf = tff.newTransformer();
        tf.transform(new DOMSource(document), new StreamResult(new File(xml_path)));
    }
}

Student类:

package com.kexin.day2;

public class Student {
    private String idcard;
    private String examid;
    private String name;
    private String location;
    private String grade;
    public String getIdcard() {
        return idcard;
    }
    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }
    public String getExamid() {
        return examid;
    }
    public void setExamid(String examid) {
        this.examid = examid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }
    public String getGrade() {
        return grade;
    }
    public void setGrade(String grade) {
        this.grade = grade;
    }

}

stu_info.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<exam>
    <stu examid="222" idcard="111">
        <name>张三</name>
        <location>济南</location>
        <grade>99</grade>
    </stu>
    <stu examid="142" idcard="325">
        <name>李四</name>
        <location>青岛</location>
        <grade>88</grade>
    </stu>
</exam>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小黄鸭and小黑鸭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值