search

XML-DOM parsing case

Feb 24, 2017 pm 03:12 PM

[Title]: Implement a simple console program based on XML files, which can check student scores, add students, delete students, etc.

xml file is saved in the src/com/dom/exercise folder, its format is as follows:

<?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>

This can be said to be the simplest program, slightly The complicated point is that it must be implemented based on XML files, so DOM parsing must be used here. SAX cannot be used because SAX parsing can only read XML files and cannot update them.


1. First write StudentBean, as follows:

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. Write the most critical StudentService class, which performs XML document Various operations

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. Write the main test program
Achieve a simple interface:

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. Running results
XML-DOM parsing case


The key to the problem is still DOM parsing XML and performing crud operations on XML.

[Title]: Implement a simple console program based on XML files, which can check student scores, add students, delete students, etc.

xml file is saved in the src/com/dom/exercise folder. Its format is as follows:

<?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>

This can be said to be the simplest program, a little more complicated. It is implemented based on XML files, so DOM parsing must be used here. SAX cannot be used because SAX parsing can only read XML files and cannot update them.


1. First write StudentBean, as follows:

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. Write the most critical StudentService class, which performs XML document Various operations

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. Write the main test program
Achieve a simple interface:

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. Running results
XML-DOM parsing case


The key to the problem is still DOM parsing XML and performing crud operations on XML.

The above is the content of the XML-DOM parsing case. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
RSS in XML: Unveiling the Core of Content SyndicationRSS in XML: Unveiling the Core of Content SyndicationApr 22, 2025 am 12:08 AM

The implementation of RSS in XML is to organize content through a structured XML format. 1) RSS uses XML as the data exchange format, including elements such as channel information and project list. 2) When generating RSS files, content must be organized according to specifications and published to the server for subscription. 3) RSS files can be subscribed through a reader or plug-in to automatically update the content.

Beyond the Basics: Advanced RSS Document FeaturesBeyond the Basics: Advanced RSS Document FeaturesApr 21, 2025 am 12:03 AM

Advanced features of RSS include content namespaces, extension modules, and conditional subscriptions. 1) Content namespace extends RSS functionality, 2) Extended modules such as DublinCore or iTunes to add metadata, 3) Conditional subscription filters entries based on specific conditions. These functions are implemented by adding XML elements and attributes to improve information acquisition efficiency.

The XML Backbone: How RSS Feeds are StructuredThe XML Backbone: How RSS Feeds are StructuredApr 20, 2025 am 12:02 AM

RSSfeedsuseXMLtostructurecontentupdates.1)XMLprovidesahierarchicalstructurefordata.2)Theelementdefinesthefeed'sidentityandcontainselements.3)elementsrepresentindividualcontentpieces.4)RSSisextensible,allowingcustomelements.5)Bestpracticesincludeusing

RSS & XML: Understanding the Dynamic Duo of Web ContentRSS & XML: Understanding the Dynamic Duo of Web ContentApr 19, 2025 am 12:03 AM

RSS and XML are tools for web content management. RSS is used to publish and subscribe to content, and XML is used to store and transfer data. They work with content publishing, subscriptions, and update push. Examples of usage include RSS publishing blog posts and XML storing book information.

RSS Documents: The Foundation of Web SyndicationRSS Documents: The Foundation of Web SyndicationApr 18, 2025 am 12:04 AM

RSS documents are XML-based structured files used to publish and subscribe to frequently updated content. Its main functions include: 1) automated content updates, 2) content aggregation, and 3) improving browsing efficiency. Through RSSfeed, users can subscribe and get the latest information from different sources in a timely manner.

Decoding RSS: The XML Structure of Content FeedsDecoding RSS: The XML Structure of Content FeedsApr 17, 2025 am 12:09 AM

The XML structure of RSS includes: 1. XML declaration and RSS version, 2. Channel (Channel), 3. Item. These parts form the basis of RSS files, allowing users to obtain and process content information by parsing XML data.

How to Parse and Utilize XML-Based RSS FeedsHow to Parse and Utilize XML-Based RSS FeedsApr 16, 2025 am 12:05 AM

RSSfeedsuseXMLtosyndicatecontent;parsingtheminvolvesloadingXML,navigatingitsstructure,andextractingdata.Applicationsincludebuildingnewsaggregatorsandtrackingpodcastepisodes.

RSS Documents: How They Deliver Your Favorite ContentRSS Documents: How They Deliver Your Favorite ContentApr 15, 2025 am 12:01 AM

RSS documents work by publishing content updates through XML files, and users subscribe and receive notifications through RSS readers. 1. Content publisher creates and updates RSS documents. 2. The RSS reader regularly accesses and parses XML files. 3. Users browse and read updated content. Example of usage: Subscribe to TechCrunch's RSS feed, just copy the link to the RSS reader.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools