Current location - Quotes Website - Signature design - About java and xml
About java and xml

Generally, DOM and SAX are two original plug-ins. You only need to import the JDOM or DOM4J JAR package into your program.

The two downloaded plug-ins have their own websites. It is recommended to use JDOM, which is relatively simple. As for how to read and write, there are many examples on the Internet.

XML is used globally. The structured language is becoming more and more popular among people, and various development platforms (such as Microsoft Studio series, Oracle series, Inprise Borland series, etc.) also use support for XML development as one of their promotional slogans. Since the e-government development that the author is engaged in introduced XML earlier, I have experienced many benefits. XML data is used to exchange information in many projects, which saves a lot of trouble. There is no need to formulate complicated data formats. Using XML data is easy and convenient. Expression is also helpful for front-line developers to track and debug.

The author has previously published related articles, such as the article "A Brief Analysis of XML Programming in Delphi". Interested readers can search it on Google (), and many media have reprinted it. What I want to discuss today is about XML programming in JAVA. I hope it will be helpful to new and old readers who are or want to learn XML programming.

In XML applications, the most commonly used and most practical thing is the reading and writing of XML files, so the author makes a brief analysis through reading and writing a simple XML file. You can first create an XML file with the following structure in any text editor, which is similar to the HTML structure, but the XML semantics are stricter, and the starting tags must be paired, such as "〈Student Roster〉" and "〈/Student Roster〉" correspond , you don’t have to worry about the number of spaces, but they are generally written in indented form for easy reading. Name this file Input.xml. You can open it in any browser that supports XML and test it. If the input is correct, you can see the tree representation structure of this file in the browser. If you are still unfamiliar with the XML structure, it is recommended that you first read the description of XML files in the article "A Brief Analysis of XML Programming in Delphi".

Input.xml

[code:1:af65f1d5b3]

lt;?xml version="1.0" encoding="GB2312"?gt;

p>

lt;Student rostergt;

lt;Student gender = "male"gt;

lt;Namegt;Li Hualt;/Namegt;

lt;agegt;14lt;/agegt;

lt;telephonegt;6287555lt;/telephonegt;

lt;/studentgt;

lt; p>

lt; Student gender = "male"gt;

lt; Namegt; Zhang Sanlt;/Namegt;

lt; Agegt; 16lt;/ Age gt;

lt; Phone gt; 8273425lt; / Phone gt;

lt; / Students gt;

lt; / Student roster gt;

[/code: 1: af65f1d5b3]

After the preparation work is completed, then start writing the substantive JAVA code.

In order to save the information read from the XML file, you need to first create a simple Bean to save the student information, named StudentBean, the code is as follows:

StudentBean.java

[code :1:af65f1d5b3]

public class StudentBean {

private String sex; //Student gender

private String name; //Student name

private int age; //Student age

private String phone; //Phone number

public void setSex(String s) {

sex = s;

}

public void setName(String s) {

name = s;

}

public void setAge(int a) {

age = a;

}

public void setPhone(String s) {

phone = s;

}

public String getSex() {

return sex;

}

public String getName() {

return name;

}

public int getAge() {

return age;

}

public String getPhone() {

return phone;

}

}

[/code: 1: af65f1d5b3]

Write the XML test class later,

TESTXml.java

[code: 1: af65f1d5b3]

import java.io.*; //Java basic package, including various IO operations

import java.util.*; //Java basic package, including various standard data structure operations

import javax.xml.parsers.*; //XML parser interface

import org.w3c.dom.*; //XML DOM implementation

import org.apache.crimson.tree.XmlDocument; // Used to write XML files

public class XMLTest {

Vector student_Vector;

XMLTest() {

}

//In order to save multiple student information, you have to use a collection class (not a collection in a simple sense, a collection in JAVA is the concept of a collection framework, Including vectors, lists, hash tables, etc.), the Vector vector class is used here. It is defined in the XMLTest test class and named student_Vector. Then define two methods readXMLFile and writeXMLFile to implement reading and writing operations.

The code is as follows:

private void readXMLFile(String inFile) throws Exception {

//To prepare for parsing XML, create a DocumentBuilderFactory instance and specify DocumentBuilder

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

DocumentBuilder db = null;

try {

db = dbf.newDocumentBuilder();

}

catch (ParserConfigurationException pce) {

System.err.println(pce); //Output exception information when an exception occurs, and then exit, the same below

System.exit(1);

}

Document doc = null;

try {

doc = db.parse( inFile);

}

catch (DOMException dom) {

System.err.println(dom.getMessage());

System.exit(1);

}

catch (IOException ioe) {

System.err.println(ioe);

System.exit(1);

}

//The following is the whole process of parsing XML. It is relatively simple. First, take the root element "Student Roster"

Element root = doc.getDocumentElement();

//Get the "student" element list

NodeList students = root.getElementsByTagName("student");

for (int i = 0; i lt; students.getLength(); i ) {

//Get each "student" element in turn

Element student = (Element ) students.item(i);

//Create one

Student Bean instance

StudentBean studentBean = new StudentBean();

//Get the student’s gender attribute

studentBean.setSex(student.getAttribute("Gender "));

//Get the "name" element, the following is similar

NodeList names = student.getElementsByTagName("name");

if ( names.getLength() == 1) {

Element e = (Element) names.item(0);

Text t = (Text) e.getFirstChild();

studentBean.setName(t.getNodeValue());

}

NodeList ages = student.getElementsByTagName("Age");

if (ages.getLength() == 1) {

Element e = (Element) ages.item(0);

Text t = (Text) e.getFirstChild( );

studentBean.setAge(Integer.parseInt(t.getNodeValue()));

}

NodeList phones = student.getElementsByTagName("Phone" );

if (phones.getLength() == 1) {

Element e = (Element) phones.item(0);

Text t = (Text) e.getFirstChild();

studentBean.setPhone(t.getNodeValue());

}

student_Vector.add(studentBean);

}

}

>

private void writeXMLFile(String outFile) throws Exception {

//To prepare for parsing XML, create a DocumentBuilderFactory instance and specify DocumentBuilder

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance() ;

DocumentBuilder db = null;

try {

db = dbf.newDocumentBuilder();

}

catch (ParserConfigurationException pce) {

System.err.println(pce);

System.exit(1);

}

Document doc = null;

doc = db.newDocument();

//The following is the process of creating XML document content. First, create the root element "Student Roster"

Element root = doc.createElement("Student Roster");

//Add the document to the root element

doc.appendChild(root);

//Get the Bean list of student information

for (int i = 0; i lt; student_Vector.size(); i) {

//In sequence Get the information of each student

StudentBean studentBean = (StudentBean) student_Vector.get(i);

//Create the "student" element and add it to the root element

Element student = doc.createElement("student");

student.setAttribute("gender", studentBean.getSex());

root.appendChild(student);

//Create the "name" element and add it under the student, the same below

Element name = doc.createElement("name");

student. appendChild(name);

Text tName = doc.crea

teTextNode(studentBean.getName());

name.appendChild(tName);

Element age = doc.createElement("age");

student .appendChild(age);

Text tAge = doc.createTextNode(String.valueOf(studentBean.

getAge()));

age.appendChild( tAge);

Element phone = doc.createElement("phone");

student.appendChild(phone);

Text tPhone = doc.createTextNode( studentBean.getPhone());

phone.appendChild(tPhone);

}

//Output the XML document to the specified file

FileOutputStream outStream = new FileOutputStream(outFile);

OutputStreamWriter outWriter = new OutputStreamWriter(outStream);

( (XmlDocument) doc).write(outWriter, "GB2312") ;

outWriter.close();

outStream.close();

}

//Finally add the test main function, As follows:

public static void main(String[] args) throws Exception {

//Create a test instance

XMLTest xmlTest = new XMLTest();

//Initialize vector list

xmlTest.student_Vector = new Vector();

System.out.println("Start reading the Input.xml file");

xmlTest.readXMLFile("Input.xml");

System.out.println("Reading completed, start writing Out

put.xml file");

xmlTest.writeXMLFile("Output.xml");

System.out.println("Write completed");

System.in.read();

}

}[/code: 1: af65f1d5b3]

Save StudentBean and XMLTest, and Input.xml is saved in the working directory. If you enter carefully and do not type the wrong letters, you can see "Write completed". Check whether the Output.xml file and the Input.xml file are the same. If you find any problems during the debugging process, please contact the author via E-Mail: nbDeveloper@hotmail.com [/code]