Use xml files as a small database to add, delete, modify, and query simple instances for students. add, delete, and delete xml files.

Source: Internet
Author: User

Use xml files as a small database to add, delete, modify, and query simple instances for students. add, delete, and delete xml files.

1. xml file:

<? xml version = "1.0" encoding = "UTF-8"?> <Students>
 <student id = "2">
  <name> ttt </ name>
  <age> 44 </ age>
 </ student>
 <student id = "3">
  <name> linda2 </ name>
  <age> 22 </ age>
 </ student>
 <student id = "4">
  <name> linda3 </ name>
  <age> 23 </ age>
 </ student>
 <student id = "5">
  <name> jack </ name>
  <age> 2 </ age>
 </ student>
 <student id = "1">
   <name> yyh1 </ name>
   <age> 22 </ age>
 </ student>
</ Students>
2. Java code

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

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
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.w3c.dom.Text;
import org.xml.sax.SAXException;

// In the student management system, the student ID is unique, and the name may be repeated
public class StudentManager {
  public static void main (String [] args) {
    try {
      Document doc = Domutils.getDoc (new File ("relative path of xml file"));
      Scanner input = new Scanner (System.in);
      System.out.println ("Welcome to the student management system \ n \ n \ nPlease enter what you want to do: \ n1. Add student information \ n2. Delete student information \ n3. Modify student information \ n (Please Enter the previous serial number) ");
      int num = input.nextInt ();
      if (num == 1) {
        addStudent (doc);
      } else if (num == 2) {
        delStudent (doc);
      } else if (num == 3) {
        updStudent (doc);
      }
    } catch (SAXException e) {
      e.printStackTrace ();
    } catch (IOException e) {
      e.printStackTrace ();
    } catch (ParserConfigurationException e) {
      e.printStackTrace ();
    }
  }
  // Edit student information
  private static void updStudent (Document doc) {
    Element updStudent = null;
    Scanner input = new Scanner (System.in);
    System.out.println ("Please enter the student ID of the student you want to modify:");
    String studentid = input.nextLine ();
    System.out.println ("Please enter the name of the new student:");
    String newName = input.nextLine ();
    System.out.println ("Please enter the age of the new student:");
    String newAge = input.nextLine ();
    
    // List each student, for loop to determine which student you want to modify the information
    NodeList list = doc.getElementsByTagName ("student");
    for (int i = 0; i <list.getLength (); i ++) {
      if (studentid.equals (list.item (i) .getAttributes (). getNamedItem ("id"). getNodeValue ())) {
        updStudent = (Element) doc.getElementsByTagName ("student"). item (i) .getFirstChild (). getParentNode ();
        // Assign new value to the student's name attribute
        updStudent.getElementsByTagName ("name"). item (i) .getFirstChild (). setNodeValue (newName);
        // Assign new value to student's age attribute
        updStudent.getElementsByTagName ("age"). item (i) .getFirstChild (). setNodeValue (newAge);
        
      } else {
        break;
      }
    }
    // Find the root element and persist the modified element to the file
    Element root = doc.getDocumentElement ();
    transform (root);
    System.out.println (updStudent);
  }
  // Delete student information
  private static void delStudent (Document doc) {
    Scanner input = new Scanner (System.in);
    // Enter the student ID of the student you want to delete
    System.out.println ("Please enter the student ID to delete:");
    String studentid = input.nextLine ();
    Element root = doc.getDocumentElement ();
    
    // List students into a table, perform traversal, find the students with corresponding student numbers
    NodeList list = doc.getElementsByTagName ("student");
    for (int i = 0; i <list.getLength (); i ++) {
    if ((studentid) .equals (list.item (i) .getAttributes (). getNamedItem ("id"). getNodeValue ()))
      Element delStudent = (Element) doc.getElementsByTagName ("student"). Item (i) .getFirstChild (). GetParentNode ();
        root.removeChild (delStudent);
        break;
      } else {
        System.out.println ("No such student");
        break;
      }
    }
    // Persistence to file
    transform (root);
  }
  
  // Add student information
  private static void addStudent (Document doc) {
// System.out.println (doc.getElementsByTagName ("student"). Item (1) .getAttributes (). GetNamedItem ("id"). GetNodeValue ());
    Element root = doc.getDocumentElement ();
    // Enter from the console
    Scanner input = new Scanner (System.in);
    System.out.println ("Please enter the student's serial number: id =");
     
    // Place students in a list to see if the student ID of the student we want to add already exists. If so, you need to change the student ID of the newly added student
    NodeList list = doc.getElementsByTagName ("student");
    String studentid = input.nextLine ();
    for (int i = 0; i <list.getLength (); i ++) {
      if (studentid.equals (list.item (i) .getAttributes (). getNamedItem ("id"). getNodeValue ())) {
        System.out.println ("The serial number student table already exists, please re-enter a new serial number:");
         studentid = input.nextLine ();
      } else {
        break;
      }
    }
    
    System.out.println ("Please enter the name of the student to be added: name =");
    String name_value = input.nextLine ();
    System.out.println ("Please enter the age of students to be added: age =");
    String age_value = input.nextLine ();
    
    // Create a node
    Element student = doc.createElement ("student");
    Element name = doc.createElement ("name");
    Element age = doc.createElement ("age");
    Text namText = doc.createTextNode (name_value);
    Text ageText = doc.createTextNode (age_value);
    // Relationship between related nodes
    root.appendChild (student);
    student.appendChild (name);
    student.appendChild (age);
    student.setAttribute ("id", studentid);
    name.appendChild (namText);
    age.appendChild (ageText);
    // Persistence to file
    transform (root);
    
  }
  // Method to persist to file
  private static void transform (Element root)
      throws TransformerFactoryConfigurationError {
    TransformerFactory factory = TransformerFactory.newInstance ();
    try {
      Transformer tf = factory.newTransformer ();
      tf.transform (new DOMSource (root), new StreamResult (new File ("src / com / briup / dom / student.xml")));
    } catch (TransformerConfigurationException e) {
      e.printStackTrace ();
    } catch (TransformerException e) {
      e.printStackTrace ();
    }
  }
}
2. Dom parsing file (encapsulate the part that gets the parsing file)

import java.io.File;
import java.io.IOException;
import java.nio.file.attribute.AclEntry.Builder;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

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

public class Domutils {
  public static Document getDoc (File file) throws SAXException, IOException, ParserConfigurationException {
// Get factory mode
    DocumentBuilderFactory factory =
        DocumentBuilderFactory.newInstance ();
// Get the builder object
      DocumentBuilder builder = factory.newDocumentBuilder ();
// Load the file to be parsed into a tree-like file and start the analysis
      Document document = builder.parse (file);
    return document;
  }
}
The above example uses the xml file as a small database, and the simple example of adding, deleting, and modifying the students is all the content that the editor has shared with you. I hope that I can give you a reference, and I hope you will support the home of helpers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.