Brief Analysis of the XML programming of Java

xiaoxiao2021-03-06  1

XML is a global structured language, which is increasingly favored by people, and various development platforms (such as Microsoft Studio series, Oracle series, Inprise Borland series, etc.) also support XML development as one of the propaganda slogans. Since the e-government development of the author has an earlier introduction of XML, it tastes many sweets, using XML data exchange information in many projects, saves many troubles, do not use the data format of the lock, easy to use XML data easy Expression, also facilitates first-line developers track debugging. The author has previously published a related article, such as "Analysis of XML Programming in Delphi", interested readers can go to Google Network ( to search, there are many media reprint. Today, I want to explore the XML programming in Java, I hope to help new and old readers who are being programmed to learn XML. In XML applications, the most commonly used most practical is the read and write of the XML file, so the author briefly analyzes through a simple XML file reading. The XML files that can be established in any text editor, similar to the HTML structure, but XML semantics is strict, and the starting mark must be paired, such as "" and "" How many spaces don't have to be concerned, but it is generally written in a constant form, which is convenient for reading. Naming this file INPUT.XML, you can open the test in any support for XML, if you enter it correctly, you can see the tree representation of this file in the browse. If you also feel more unfamiliar with the XML structure, it is recommended to first look at "Analysis of XML Programming in Delphi" One Description of XML files.

Li Hua



Zhang 3

Age> 16


After the preparation work is finished, the Java code that will begin to write a qualitative. In order to save information read from the XML file, you need to build a simple bean to save the student information, named StudentBean, the code is as follows:

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 agn;


Public String getphone () {

Return Phone;



After writing XML test classes, the author named XMLTEST, in order to read and write XML files, need to import as follows, "//", for note, the author's environment is JDK 1.3.1_04, in JDK 1.4.0 The test also passed the XML interpreter with Apache's crimson, can go to the Apache home page to upload.

Import *; // java foundation, 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; // Write XML file to use

In order to preserve multiple student information, you have to use a collection class (not a collection of simple sense, the collection of java is the concept of the collection framework, including vector, list, hash table, etc.), here uses the Vector vector class. Define in the XMLTEST test class, named Student_Vector. Then define two methods ReadXmlFile and WriteXMLFILE to implement read and write operations. code show as below:

Private void readxmlfile (string infile) throws exception {

/ / Create a DocumentBuilder instance for parsing XML, creating a DocumentBuilderFactory instance

DocumentBuilderFactory DBF = DocumentBuilderFactory.newinstance ();

DocumentBuilder DB = NULL;

Try {

DB = dbf.newdocumentbuilder ();

} catch (ParserConfigurationException PCE) {

System.err.println (PCE); // Output exception information, then exit, the same

System.exit (1);


Document Doc = NULL;

Try {

DOC = db.parse (Infile);

} catch (domexception DOM) {

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

System.exit (1);

} catch (ioexception ie) {

System.err.Println (IOE);

System.exit (1);


// The following is the whole process of parsing XML, relatively simple, first take root element "student flower name"

Element root = doc.getdocumentelement ();

// Take a list of "students" elements

Nodelist students = root.getElementsBytagname ("student");

For (int i = 0; i

// take each "student" element

Element Student = (Element) Students.Item (i);

// Create a BEAN instance of a student

StudentBean StudentBean = new studentbean ();

// Take the students' gender attributes StudentBean.SetSex (Student.GetaTRibute);

// Take the "Name" element, the following class

Nodelist name = 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 phone = student.getlementsBytagname ("phone");

IF (Phones.getLength () == 1) {

ELEMENT E = (Element) Phones.Item (0);

Text t = (text) E.GETFIRSTCHILD ();



Student_vector.add (studentbean);



Private void writexmlfile (string outfile) throws exception {

/ / Create a DocumentBuilder instance for parsing XML, creating a DocumentBuilderFactory instance

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 establishing the content of XML document, first establish a root element "student roster"

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

// Root elements Add a document

Doc.Appendchild (root);

// Take the bean list of student information

For (int i = 0; i

// take each student's information

StudentBean StudentBean = (studentbean) Student_Vector.get (i);

// Establish a "student" element to add to the root element

Element Student = Doc.createElement ("Student");

Student.SetAttribute ("Gender", StudentBean.getSex ());

Root.Appendchild (student);

// Establish a "name" element, add it to the student below, the following Element Name = Doc.createElement; "Name");

Student.Appendchild (name);

Text TName = Doc.createTextNode (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 {

// Establish a test instance


// Initialization vector list

Xmltest.student_vector = new vector ();

System.out.println ("Start Read INPUT.XML File");

XMLTest.ReadxmlFile ("Input.xml");

System.out.println ("After reading, start writing Output.xml files);

Xmltest.writexmlfile ("Output.xml");

System.out.println ("write completion");


Ok, save StudentBean and XMLTest, save the Input.xml to the working directory. If you enter a very careful, you can see "Write Finish", you can see the "write completion", go to the output.xml file and the input.xml file is not the same.


New Post(0)