旗下导航:搜·么
当前位置:网站首页 > XML教程 > 正文

XML—DOM剖析案例【XML教程】,XML,DOM

作者:搜教程发布时间:2019-12-01分类:XML教程浏览:30评论:0


导读:【题目】:基于XML文件完成一个浅易的控制台顺序,能够检察门生效果,增加门生,删除门生等。xml文件保存在src/com/dom/exercise文件夹下,它的花样以下:&...

【题目】:基于XML文件完成一个浅易的控制台顺序,能够检察门生效果,增加门生,删除门生等。

xml文件保存在src/com/dom/exercise文件夹下,它的花样以下:

<?xml version="1.0" encoding="utf-8" standalone="no"?><students>
    <student sid="001">
        <name>小明</name>
        <course>
            <java>90</java>
            <oracle>90</oracle>
            <vb>93</vb>
        </course>
    </student>
    <student sid="002">
        <name>小李</name>
        <course>
            <java>78</java>
            <oracle>86</oracle>
            <vb>98</vb>
        </course>
    </student>
    <student sid="003">
        <name>小王</name>
        <course>
            <java>89</java>
            <oracle>83</oracle>
            <vb>95</vb>
        </course>
    </student></students>

这个能够说是最简朴的顺序了,轻微庞杂的一点是它要基于XML文件来完成,所以这里一定要运用DOM剖析,SAX不能用是由于SAX剖析只能读取XML文件而不能更新。

1.起首编写StudentBean,以下:

package com.dom.exercise;public class Student {
    private String id = null;    
    private String name = null;    
    private int score_java;    
    private int score_oracle;    
    private int score_vb;    
    public Student() {
    }    public Student(String id, String name, int score_java, int score_oracle,            
    int score_vb) {        
    super();        
    this.id = id;        
    this.name = name;        
    this.score_java = score_java;        
    this.score_oracle = score_oracle;        
    this.score_vb = score_vb;
    }    public String getId() {        
    return id;
    }    public void setId(String id) {        
    this.id = id;
    }    public String getName() {        
    return name;
    }    public void setName(String name) {        
    this.name = name;
    }    public int getScore_java() {        
    return score_java;
    }    public void setScore_java(int score_java) {        
    this.score_java = score_java;
    }    public int getScore_oracle() {        
    return score_oracle;
    }    public void setScore_oracle(int score_oracle) {        
    this.score_oracle = score_oracle;
    }    public int getScore_vb() {        
    return score_vb;
    }    public void setScore_vb(int score_vb) {        
    this.score_vb = score_vb;
    }
}

2.编写最症结的StudentService类,它对XML文档举行种种操纵

import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
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.Node;
import org.w3c.dom.NodeList;
public class StudentService {

    private static Document document = null;    
    private static String path = "src/com/dom/exercise/student.xml";    
    static{        
    try{
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(path);
        }catch(Exception e){
            System.out.println("初始化失利...");
            e.printStackTrace();
        }
    }    /**
     * 猎取一切门生信息
     * @return
     */
    public static ArrayList<Student> readAll(){
        ArrayList<Student> array = new ArrayList<Student>();
        NodeList students  = document.getElementsByTagName("student");        
        for (int i = 0; i < students.getLength(); i++) {
            Element node_student = (Element)students.item(i);
            String id = node_student.getAttribute("sid");
            Node node_name = node_student.getElementsByTagName("name").item(0);
            String name = node_name.getTextContent();
            Element node_course = (Element)node_student.getElementsByTagName("course").item(0);
            Node course_java = node_course.getElementsByTagName("java").item(0);
            Node course_oracle = node_course.getElementsByTagName("oracle").item(0);
            Node course_vb = node_course.getElementsByTagName("vb").item(0);            
            int score_java = Integer.parseInt(course_java.getTextContent());            
            int score_oracle = Integer.parseInt(course_oracle.getTextContent());            
            int score_vb = Integer.parseInt(course_vb.getTextContent());

            Student student = new Student(id, name, score_java, score_oracle, score_vb);
            array.add(student);
        }        return array;
    }    /**
     * 依据ID猎取一个门生的信息
     * @param sid
     * @return
     */
    public static Student getStudentById(String sid){
        NodeList students  = document.getElementsByTagName("student");        
        for (int i = 0; i < students.getLength(); i++) {
            Element node_student = (Element)students.item(i);
            String id = node_student.getAttribute("sid");            
            if(!id.equals(sid)){                
            continue;
            }
            Node node_name = node_student.getElementsByTagName("name").item(0);
            String name = node_name.getTextContent();
            Element node_course = (Element)node_student.getElementsByTagName("course").item(0);
            Node course_java = node_course.getElementsByTagName("java").item(0);
            Node course_oracle = node_course.getElementsByTagName("oracle").item(0);
            Node course_vb = node_course.getElementsByTagName("vb").item(0);            
            int score_java = Integer.parseInt(course_java.getTextContent());            
            int score_oracle = Integer.parseInt(course_oracle.getTextContent());            
            int score_vb = Integer.parseInt(course_vb.getTextContent());

            Student student = new Student(id, name, score_java, score_oracle, score_vb);            
            return student;
        }        return null;
    }    /**
     * 增加门生
     * @param student
     */
    public static void addStudent(Student student){
        Element stu = document.createElement("student");
        stu.setAttribute("sid", student.getId());
        Element name = document.createElement("name");
        name.setTextContent(student.getName());
        Element course = document.createElement("course");
        Element score_java = document.createElement("java");
        Element score_oracle = document.createElement("oracle");
        Element score_vb = document.createElement("vb");
        score_java.setTextContent(String.valueOf(student.getScore_java()));
        score_oracle.setTextContent(String.valueOf(student.getScore_oracle()));
        score_vb.setTextContent(String.valueOf(student.getScore_vb()));

        course.appendChild(score_java);
        course.appendChild(score_oracle);
        course.appendChild(score_vb);
        stu.appendChild(name);
        stu.appendChild(course);
        document.getDocumentElement().appendChild(stu);
        update(document, path);
    }    /**
     * 依据ID删除一个门生
     * @param sid
     */
    public static void deleteStudentById(String sid){
        NodeList students = document.getElementsByTagName("student");        
        for (int i = 0; i < students.getLength(); i++) {
            Element student = (Element)students.item(i);            
            if(student.getAttribute("sid").equals(sid)){
                student.getParentNode().removeChild(student);
            }
        }
        update(document,path);
    }    /**
     * 更新到文件
     * @param document
     * @param path
     */
    public static void update(Document document,String path){        try{
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(new DOMSource(document), new StreamResult(new File(path)));
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}

3.编写主测试顺序
完成浅易界面:

package com.dom.exercise;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);        
        boolean flag = true;        
        while(flag){            
        // 显现操纵界面
            System.console();
            System.out.println("*********************操纵界面*********************");
            System.out.println("\t\t1.查询一切门生的效果");
            System.out.println("\t\t2.根据ID查询门生效果 ");
            System.out.println("\t\t3.增加一个门生");
            System.out.println("\t\t4.根据ID删除一个门生");
            System.out.println("\t\t0.退出体系");
            System.out.println("************************************************");            
            // 猎取用户的操纵
            String operate = scanner.next();            
            if ("1".equals(operate)) {
                ArrayList<Student> students = StudentService.readAll();
                System.out.println("一切的门生信息以下:");
                System.out.println("Name\tID\tJava\tOracle\tVB");                
                for (Student student : students) {
                    System.out.println(student.getName() + "\t" + student.getId()
                            + "\t" + student.getScore_java() + "\t"
                            + student.getScore_oracle() + "\t"
                            + student.getScore_vb());
                }
            }else if("2".equals(operate)){
                System.out.println("请输入要查询的门生ID:");
                String sid = scanner.next();
                Student student = StudentService.getStudentById(sid);
                System.out.println("学号为"+sid+"的门生的信息以下:");
                System.out.println("Name\tID\tJava\tOracle\tVB");
                System.out.println(student.getName() + "\t" + student.getId()
                        + "\t" + student.getScore_java() + "\t"
                        + student.getScore_oracle() + "\t"
                        + student.getScore_vb());
            }else if("3".equals(operate)){
                System.out.println("请输入要增加的门生ID:");
                String sid = scanner.next();
                System.out.println("请输入要增加的门生姓名:");
                String name = scanner.next();
                System.out.println("请输入要增加的门生Java效果:");                
                int score_java = Integer.parseInt(scanner.next());
                System.out.println("请输入要增加的门生Oracle效果:");                
                int score_oracle = Integer.parseInt(scanner.next());
                System.out.println("请输入要增加的门生VB效果:");                
                int score_vb = Integer.parseInt(scanner.next());
                Student student = new Student(sid, name, score_java, score_oracle, score_vb);
                StudentService.addStudent(student);
                System.out.println("增加胜利!");
            }else if("4".equals(operate)){
                System.out.println("请输入要删除的门生的ID:");
                String sid = scanner.next();
                StudentService.deleteStudentById(sid);
                System.out.println("删除胜利!");
            }
            System.out.println("是不是继承?(Y/N)");
            flag = scanner.next().trim().toLowerCase().equals("y")?true:false;
        }
        scanner.close();
    }
}

4.运转效果

题目的症结还是DOM剖析XML,对XML举行crud操纵。

【题目】:基于XML文件完成一个浅易的控制台顺序,能够检察门生效果,增加门生,删除门生等。

xml文件保存在src/com/dom/exercise文件夹下,它的花样以下:

<?xml version="1.0" encoding="utf-8" standalone="no"?><students>
    <student sid="001">
        <name>小明</name>
        <course>
            <java>90</java>
            <oracle>90</oracle>
            <vb>93</vb>
        </course>
    </student>
    <student sid="002">
        <name>小李</name>
        <course>
            <java>78</java>
            <oracle>86</oracle>
            <vb>98</vb>
        </course>
    </student>
    <student sid="003">
        <name>小王</name>
        <course>
            <java>89</java>
            <oracle>83</oracle>
            <vb>95</vb>
        </course>
    </student></students>

这个能够说是最简朴的顺序了,轻微庞杂的一点是它要基于XML文件来完成,所以这里一定要运用DOM剖析,SAX不能用是由于SAX剖析只能读取XML文件而不能更新。

1.起首编写StudentBean,以下:

package com.dom.exercise;public class Student {
    private String id = null;    
    private String name = null;    
    private int score_java;    
    private int score_oracle;    
    private int score_vb;    
    public Student() {
    }    public Student(String id, String name, int score_java, int score_oracle,            
    int score_vb) {        
    super();        
    this.id = id;        
    this.name = name;        
    this.score_java = score_java;        
    this.score_oracle = score_oracle;        
    this.score_vb = score_vb;
    }    public String getId() {        
    return id;
    }    public void setId(String id) {        
    this.id = id;
    }    public String getName() {        
    return name;
    }    public void setName(String name) {        
    this.name = name;
    }    public int getScore_java() {        
    return score_java;
    }    public void setScore_java(int score_java) {        
    this.score_java = score_java;
    }    public int getScore_oracle() {        
    return score_oracle;
    }    public void setScore_oracle(int score_oracle) {        
    this.score_oracle = score_oracle;
    }    public int getScore_vb() {        
    return score_vb;
    }    public void setScore_vb(int score_vb) {        
    this.score_vb = score_vb;
    }
}

2.编写最症结的StudentService类,它对XML文档举行种种操纵

import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
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.Node;
import org.w3c.dom.NodeList;
public class StudentService {

    private static Document document = null;    
    private static String path = "src/com/dom/exercise/student.xml";    
    static{        
    try{
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.parse(path);
        }catch(Exception e){
            System.out.println("初始化失利...");
            e.printStackTrace();
        }
    }    /**
     * 猎取一切门生信息
     * @return
     */
    public static ArrayList<Student> readAll(){
        ArrayList<Student> array = new ArrayList<Student>();
        NodeList students  = document.getElementsByTagName("student");        
        for (int i = 0; i < students.getLength(); i++) {
            Element node_student = (Element)students.item(i);
            String id = node_student.getAttribute("sid");
            Node node_name = node_student.getElementsByTagName("name").item(0);
            String name = node_name.getTextContent();
            Element node_course = (Element)node_student.getElementsByTagName("course").item(0);
            Node course_java = node_course.getElementsByTagName("java").item(0);
            Node course_oracle = node_course.getElementsByTagName("oracle").item(0);
            Node course_vb = node_course.getElementsByTagName("vb").item(0);            
            int score_java = Integer.parseInt(course_java.getTextContent());            
            int score_oracle = Integer.parseInt(course_oracle.getTextContent());            
            int score_vb = Integer.parseInt(course_vb.getTextContent());

            Student student = new Student(id, name, score_java, score_oracle, score_vb);
            array.add(student);
        }        return array;
    }    /**
     * 依据ID猎取一个门生的信息
     * @param sid
     * @return
     */
    public static Student getStudentById(String sid){
        NodeList students  = document.getElementsByTagName("student");        
        for (int i = 0; i < students.getLength(); i++) {
            Element node_student = (Element)students.item(i);
            String id = node_student.getAttribute("sid");            
            if(!id.equals(sid)){                
            continue;
            }
            Node node_name = node_student.getElementsByTagName("name").item(0);
            String name = node_name.getTextContent();
            Element node_course = (Element)node_student.getElementsByTagName("course").item(0);
            Node course_java = node_course.getElementsByTagName("java").item(0);
            Node course_oracle = node_course.getElementsByTagName("oracle").item(0);
            Node course_vb = node_course.getElementsByTagName("vb").item(0);            
            int score_java = Integer.parseInt(course_java.getTextContent());            
            int score_oracle = Integer.parseInt(course_oracle.getTextContent());            
            int score_vb = Integer.parseInt(course_vb.getTextContent());

            
            Student student = new Student(id, name, score_java, score_oracle, score_vb);            
            return student;
        }        return null;
    }    /**
     * 增加门生
     * @param student
     */
    public static void addStudent(Student student){
        Element stu = document.createElement("student");
        stu.setAttribute("sid", student.getId());
        Element name = document.createElement("name");
        name.setTextContent(student.getName());
        Element course = document.createElement("course");
        Element score_java = document.createElement("java");
        Element score_oracle = document.createElement("oracle");
        Element score_vb = document.createElement("vb");
        score_java.setTextContent(String.valueOf(student.getScore_java()));
        score_oracle.setTextContent(String.valueOf(student.getScore_oracle()));
        score_vb.setTextContent(String.valueOf(student.getScore_vb()));

        course.appendChild(score_java);
        course.appendChild(score_oracle);
        course.appendChild(score_vb);
        stu.appendChild(name);
        stu.appendChild(course);
        document.getDocumentElement().appendChild(stu);
        update(document, path);
    }    /**
     * 依据ID删除一个门生
     * @param sid
     */
    public static void deleteStudentById(String sid){
        NodeList students = document.getElementsByTagName("student");        
        for (int i = 0; i < students.getLength(); i++) {
            Element student = (Element)students.item(i);            
            if(student.getAttribute("sid").equals(sid)){
                student.getParentNode().removeChild(student);
            }
        }
        update(document,path);
    }    /**
     * 更新到文件
     * @param document
     * @param path
     */
    public static void update(Document document,String path){        
    try{
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.transform(new DOMSource(document), new StreamResult(new File(path)));
        }catch(Exception e){
            e.printStackTrace();
        }

    }
}

3.编写主测试顺序
完成浅易界面:

package com.dom.exercise;import java.util.ArrayList;import java.util.Scanner;public class Main {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);        
        boolean flag = true;        
        while(flag){            
        // 显现操纵界面
            System.console();
            System.out.println("*********************操纵界面*********************");
            System.out.println("\t\t1.查询一切门生的效果");
            System.out.println("\t\t2.根据ID查询门生效果 ");
            System.out.println("\t\t3.增加一个门生");
            System.out.println("\t\t4.根据ID删除一个门生");
            System.out.println("\t\t0.退出体系");
            System.out.println("************************************************");            
            // 猎取用户的操纵
            String operate = scanner.next();            
            if ("1".equals(operate)) {
                ArrayList<Student> students = StudentService.readAll();
                System.out.println("一切的门生信息以下:");
                System.out.println("Name\tID\tJava\tOracle\tVB");                
                for (Student student : students) {
                    System.out.println(student.getName() + "\t" + student.getId()
                            + "\t" + student.getScore_java() + "\t"
                            + student.getScore_oracle() + "\t"
                            + student.getScore_vb());
                }
            }else if("2".equals(operate)){
                System.out.println("请输入要查询的门生ID:");
                String sid = scanner.next();
                Student student = StudentService.getStudentById(sid);
                System.out.println("学号为"+sid+"的门生的信息以下:");
                System.out.println("Name\tID\tJava\tOracle\tVB");
                System.out.println(student.getName() + "\t" + student.getId()
                        + "\t" + student.getScore_java() + "\t"
                        + student.getScore_oracle() + "\t"
                        + student.getScore_vb());
            }else if("3".equals(operate)){
                System.out.println("请输入要增加的门生ID:");
                String sid = scanner.next();
                System.out.println("请输入要增加的门生姓名:");
                String name = scanner.next();
                System.out.println("请输入要增加的门生Java效果:");                
                int score_java = Integer.parseInt(scanner.next());
                System.out.println("请输入要增加的门生Oracle效果:");                
                int score_oracle = Integer.parseInt(scanner.next());
                System.out.println("请输入要增加的门生VB效果:");                
                int score_vb = Integer.parseInt(scanner.next());
                Student student = new Student(sid, name, score_java, score_oracle, score_vb);
                StudentService.addStudent(student);
                System.out.println("增加胜利!");
            }else if("4".equals(operate)){
                System.out.println("请输入要删除的门生的ID:");
                String sid = scanner.next();
                StudentService.deleteStudentById(sid);
                System.out.println("删除胜利!");
            }
            System.out.println("是不是继承?(Y/N)");
            flag = scanner.next().trim().toLowerCase().equals("y")?true:false;
        }
        scanner.close();
    }
}

4.运转效果

题目的症结还是DOM剖析XML,对XML举行crud操纵。

以上就是XML—DOM剖析案例的内容,更多相关内容请关注ki4网(www.ki4.cn)!

标签:XMLDOM


欢迎 发表评论: