xml| programming XML, as a universal structured language, is becoming more and more popular, and various development platforms (such as the Microsoft Studio series, Oracle series, Inprise Borland series) also support 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.
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.
<?xml version= "1.0" encoding= "GB2312"?
Student Roster
Student sex = "male"
Name > Li Hua </name >
Age >14</Age
Telephone >6287555</Telephone
</Students > >
Student sex = "male"
Name > John </name >
Age >16</Age
Telephone >8273425</Telephone
</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
In order to save multiple student information, you have to use a collection class (not a simple set, the set in Java is the concept of a set frame, including vectors, lists, hash tables, and so on), and vector vectors are used here. Defined in the Xmltest test class, named Student_vector. Then two methods Readxmlfile and writexmlfile are defined to achieve read-write operations. The code is as follows:
private void Readxmlfile (String inFile) 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); Output exception information when out of exception, then exit, 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 simpler to take root element "student roster" first
Element root = Doc.getdocumentelement ();
Take the Student element list
NodeList students = root.getelementsbytagname ("student");
for (int i = 0; I students.getlength (); i++) {
Take each "student" element in turn
element student = (element) students.item (i);
Create a student's bean instance
Studentbean Studentbean = new Studentbean ();
Take the student's sex attribute
Studentbean.setsex (Student.getattribute ("gender"));
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 ());
}
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 ();
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.
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.