Java XML programming (to: beginners)

Source: Internet
Author: User
Tags microsoft studio
I personally think this article is easy to understand and worthy of recommendation.
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 promotion slogans. 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.

I have previously published related articles, such as "Analysis of XML programming in Delphi", interested readers can go to Google (http://www.google.com) to search, there is a lot of multimedia reprint. Today, I want to discuss XML programming in Java, hoping to help new and old readers who are learning or want to learn XML programming.

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 completing the preparation, I began to write substantial Java code. 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; // 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 ){
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 upload it on the Apache homepage.
Import java. Io. *; // Basic Java package, including various Io operations
Import java. util. *; // Basic Java package, including various standard data structure operations
Import javax. xml. parsers. *; // XML Parser Interface
Import org. W3C. Dom. *; // Dom Implementation of XML
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 {
// 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); // 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 entire process of parsing XML, which is relatively simple. First, take the root element "student roster"
Element root = Doc. getdocumentelement ();
// Retrieve the "student" element list
Nodelist students = root. getelementsbytagname ("student ");
For (INT I = 0; I <students. getlength (); I ++ ){
// Obtain each "student" element in sequence
Element student = (element) students. item (I );
// Create a student's bean instance
Studentbean = new studentbean ();
// Obtain the Gender attribute of the student
Studentbean. setsex (student. getattribute ("gender "));
// Obtain the "name" element, which 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 {
// 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 ();

// The following describes how to create the 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 );

// Retrieve the bean list of Student Information
For (INT I = 0; I <student_vector.size (); I ++ ){
// Obtain the information of each student in sequence
Studentbean = (studentbean) student_vector.get (I );
// Create a "student" element and add it to the root element
Element student = Doc. createelement ("student ");
Student. setattribute ("gender", studentbean. getsex ());
Root. appendchild (student );
// Create a "name" element and add it to the student, the same below
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 {
// Create a test instance
Xmltest = new xmltest ();
// 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 ");
}

Well, 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.