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. Using XML data exchange information in many projects, there is a lot of trouble, and there is no need to develop the data format of the lock, and the XML data is easy to express, which is also beneficial to the first-line developer tracking debugging.
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 "
XML Version = "1.0" encoding = "GB2312"?>
Student>
Age> 16 age>
Student>
Student Relief>
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 Age;
}
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.io. *;
// Java basic package, including various IO operations
Import java.util. *;
// Java foundation package, including various standard data structural 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 {
/ / For the analysis of XML,
Create a DocumentBuilderFactory instance, specify DocumentBuilder
DocumentBuilderFactory DBF = DocumentBuilderFactory.newinstance ();
DocumentBuilder DB = NULL;
Try {
DB = dbf.newdocumentbuilder ();
} catch (ParserConfigurationException PCE) {
System.err.println (PCE);
// Output an abnormal information when an abnormality, 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,
More simple, first take root elements "Student Relief"
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 students' gender properties StudentBean.SetSex (Student.getaTribute); // Take the "Name" element, the following class with nodelist name = student.getlementsBytagname ("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 (); StudentBean.SETPHONE (T.GETNODEVALUE ()); } Student_vector.add (studentbean); } } Private void writexmlfile (string outfile) throws exception { / / For the analysis of XML, Create a 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 establishing an XML document content, First establish a root element "student flower name" 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 "Name" element, add it to the students, 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 XMLTEST XMLTEST = New XMLTEST (); // 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. You can see "Write completion".