A brief analysis of Java XML programming

Source: Internet
Author: User
Tags exit return string xml parser microsoft studio
Xml| programming

Personally think this article is easy to understand, it is worth recommending.
As a global, structured language, XML is gaining popularity, with various development platforms (such as the Microsoft Studio series, Oracle series, Inprise Borland series, etc.) supporting XML development as one of the promotional slogans. Because the author engaged in the Electronic government development earlier introduced XML, so tasted a lot of sweetness, in many projects using XML data exchange information, save a lot of trouble, do not have to make the data format of the lock, using XML data easy to express, but also conducive to the first line of developers tracking debugging.

The author has previously published related articles, such as "Simple analysis of the XML programming in Delphi" a text, interested readers can go to Google Network (http://www.google.com) to search, there are many media reprint. What I want to discuss today is XML programming in Java, which I want to help new and old readers who are or want to learn XML programming.

In XML application, the most common and most practical is the XML file reading and writing, so the author through a simple XML file read and write to make a brief analysis. You can create an XML file of the following structure in any text editor, similar to the HTML structure, but the XML semantics is stricter, the starting tag must be paired, such as "student roster" and "〈/student roster" corresponding, the number of spaces can not care, but generally in the form of indented, easy to read. Name this file Input.xml, you can open the test in any XML-enabled browser, and if you enter it correctly, you can see the tree representation structure of the file in the browse. If you are still unfamiliar with the XML structure, it is recommended that you take a look at the XML file in the article "Simplifying XML Programming in Delphi".
<?xml version= "1.0" encoding= "GB2312"?>
< student roster >
< student gender = "male" >
< name > Li Hua </name >
< age >14</Age >
< telephone >6287555</Tel >
</Students >
< student gender = "male" >
< name > John </name >
< age >16</Age >
< telephone >8273425</Tel >
</Students >
</Student Roster >

After the preparations have been completed, the actual Java code is then written. To save the information read from an XML file, you need to first build a simple bean to hold the student information, named Studentbean, as shown in the following code:
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;
}
}

Then write the XML test class, the author named This class Xmltest, in order to read and write XML files, need to import the following Java package, "//" After the note, the author's environment is JDK 1.3.1_04, in the JDK 1.4.0 test also passed, The XML interpreter is crimson with Apache and can be uploaded to the Apache home page.
Import java.io.*; Java base Package with various IO operations
Import java.util.*; Java base package, containing 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;//write XML file to use

private void Readxmlfile (String inFile) throws Exception {
//Preparing for parsing XML, creating a Documentbuilderfactory instance, Specifies Documentbuilder
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
Documentbuilder db = null;
try {
db = Dbf.newdocumentbuilder ();
} catch (Parserconfigurationexception PCE) {
System.err.println (PCE);////Output exception information when exception, then exit, same as
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);
}
//Below is the whole process of parsing XML, which is simpler by first taking the root element "student roster"
Element root = Doc.getdocumentelement ();
//Take the Student element list
NodeList students = root.getelementsbytagname ("student");
for (int i = 0; i < students.getlength (); i++) {
///in sequence each student element
Element student = (element) Students.item (i) ;
//Create a student's bean instance
Studentbean Studentbean = new Studentbean ();
//Take the student's gender attributes
Studentbean.setsex (student.getattribute ("Sex"));
//Take the "name" element, similar to the following
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 ("Telephone");
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 parsing XML, create Documentbuilderfactory instance, 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 building the content of an XML document, first building the root element "student roster"
Element root = doc.createelement ("Student roster");
root element to add the document
Doc.appendchild (root);

A bean list of student information
for (int i = 0; i < student_vector.size (); i++) {
Take each student's information sequentially
Studentbean Studentbean = (Studentbean) student_vector.get (i);
Create the student element, add to the root element
Element student = doc.createelement ("student");
Student.setattribute ("Gender", Studentbean.getsex ());
Root.appendchild (student);
Create the "name" element and add it to the student below
Element name = doc.createelement ("name");
Student.appendchild (name);
Text tname = Doc.createtextnode (Studentbean.getname ());
Name.appendchild (Tname);

Element age = Doc.createelement ("Ages");
Student.appendchild (age);
Text Tage = Doc.createtextnode (string.valueof (Studentbean.getage ()));
Age.appendchild (Tage);

Element phone = doc.createelement ("Telephone");
Student.appendchild (phone);
Text Tphone = Doc.createtextnode (Studentbean.getphone ());
Phone.appendchild (Tphone);
}
To export an XML document to a 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 {
Set up Test instances
Xmltest xmltest = new Xmltest ();
Initialize Vector list
Xmltest.student_vector = new Vector ();

System.out.println ("Start reading Input.xml document");
Xmltest.readxmlfile ("Input.xml");

System.out.println ("read into complete, start writing output.xml document");
Xmltest.writexmlfile ("Output.xml");
System.out.println ("write complete");
}

Well, save the Studentbean and Xmltest, and save the Input.xml to the working directory. If you enter very carefully, do not hit the wrong letter, you can see "write completed", to see Output.xml file and Input.xml file is the same.



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.