XML programming in Java

Source: Internet
Author: User
Tags microsoft studio

XML, as a common structured language in the world, is becoming more and more popular, with various development platforms (such as Microsoft studio series, Oracle series, and inprise Borland series) XML development is also supported as one of the product features. Because XML was introduced earlier in e-government development, I have tasted a lot of sweetness and used XML data to exchange information in many projects, saving a lot of trouble, without the need to develop a data format for the traditional lock, XML data is easy to express, and it is also beneficial for frontline developers to track and debug.

In XML applications, the most common and practical way is to read and write XML files. Therefore, the author makes a brief analysis by reading and writing a simple XML file. You can create an XML file with the following structure in any text editor, which is similar to the HTML structure. However, the XML syntax is strict and the start tag must be paired, for example, if "student roster" corresponds to "/student roster", you do not need to care about the number of spaces, but generally write them in the form of a thumbnail to facilitate reading. Name the file input. xml. You can open it in any browser that supports XML for testing. If the input is correct, you can see the tree structure of the file in the browser. If you are still unfamiliar with the XML structure, we recommend that you first take a look at the XML file description in the document "XML programming in Delphi.

<? XML version = "1.0" encoding = "gb2312"?>
<Student roster>
<Student gender = "male">
<Name> Li Hua </Name>
<Age> 14 </age>
<Phone> 6287555 </phone>
</Student>
<Student gender = "male">
<Name> Zhang San </Name>
<Age> 16 </age>
<Phone> 8273425 </phone>
</Student>
</Student roster>

After the preparation is complete, we start to write substantial JavaCode. To save the Information read from the XML file, you must first create a simple bean to save the student information and name it studentbean. The Code is as follows:

Public class studentbean {
Private string sex; file: // Student gender
Private string name; file: // Student name
Private int age; file: // student age
Private string phone; file: // phone number

Public void setsex (string s ){
Sex = s;
}
Public void setname (string s ){
Name = s;
}
Public void setage (int ){
Age =;
}
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;
}
}

Then write the XML test class. I name this class xmltest. to read and write the XML file, import the following Java package, "//" and then describe it with comments, the author's environment is JDK 1.3.1 _ 04, which is also tested in JDK 1.4.0. The XML interpreter uses Apache crimson and can be downloaded on the Apache homepage.

Import java. Io .*;File: // JavaBasic package, including various Io operations
Import java. util .*;File: // JavaBasic package, including various standard data structure operations
Import javax. xml. parsers .*;File: // XMLParser Interface
Import org. W3C. Dom .*;File: // XMLDom implementation
Import org. Apache. Crimson. Tree. xmldocument; // used to write XML files

To save multiple student information, you must also use a collection class (not a set in a simple sense, Java's set is the concept of a collection framework, including vectors, lists, and hash tables ), the vector class is used here. Defined in the xmltest test class and named student_vector. Then we define two methods: readxmlfile and writexmlfile to implement read/write operations. The Code is as follows:

Private void readxmlfile (string infile) throws exception {
File: // prepare for XML parsing, 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); file: // output exception information when an exception occurs, and then exit, as shown 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);
}< br> file: // the whole process of parsing XML is as follows, which is relatively simple, first take the root element "student roster"
element root = Doc. getdocumentelement ();
file: // list of "student" elements
nodelist students = root. getelementsbytagname ("student");
for (INT I = 0; I file: // obtain each "student" element in sequence
element student = (element) students. item (I);
file: // create a student's bean instance
studentbean = new studentbean ();
file: // obtain the student's Gender attribute
studentbean. setsex (student. getattribute ("gender");
file: // obtain the "name" element, which is similar to
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 {
File: // prepare for XML parsing, 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 ();

File: // The following is the process of creating the XML document content. First, the root element "student roster" is created"
Element root = Doc. createelement ("student roster ");
File: // Add the document to the root element
Doc. appendchild (Root );

File: // bean list for retrieving Student Information
For (INT I = 0; I <student_vector.size (); I ++ ){
File: // obtain the information of each student in sequence.
Studentbean = (studentbean) student_vector.get (I );
File: // create a "student" element and add it to the root element.
Element student = Doc. createelement ("student ");
Student. setattribute ("gender", studentbean. getsex ());
Root. appendchild (student );
File: // create the "name" element and add it to the student.
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 );
}
File: // output the XML file 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 {
File: // create a test instance
Xmltest = new xmltest ();
File: // initialize the vector list
Xmltest. student_vector = new vector ();

System. Out. println ("starting to read the input. xml file ");
Xmltest. readxmlfile ("input. xml ");

System. Out. println ("read finished, start to write the output. xml file ");
Xmltest. writexmlfile ("output. xml ");
System. Out. println ("Write completed ");
}

Save studentbean and xmltest, and save input. XML to the working directory. If the input is very careful, you can see that the writing is complete without typing the wrong letter. Check whether the output. xml file is the same as the input. xml file.

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.