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. In many projects, the use of XML data to exchange information saves a lot of trouble, without the need to develop a complex lock data format, the use of XML data is easy to express, it is also conducive to front-line developers tracking debugging.
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.
<? Xml version = "1.0" encoding = "GB2312"?> <Br/> <student roster> <br/> <Student gender = "male"> <br/> <Name> Li Hua </Name> <br/> <age> 14 </age> <br/> <phone number> 6287555 </phone number> <br/> </student> <br/> <Student gender = "male"> <br/> <Name> Zhang San </Name> <br/> <age> 16 </age> <br/> <phone number> 8273425 </phone number> <br/> </student> <br/> </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 {<br/> private string sex; // Student gender <br/> private string name; // Student name <br/> private int age; // student age <br/> private string phone; // phone number </P> <p> Public void setsex (string s) {<br/> sex = s; <br/>}< br/> Public void setname (string s) {<br/> name = s; <br/>}< br/> Public void setage (int A) {<br/> age =; <br/>}< br/> Public void setphone (string s) {<br/> phone = s; <br/>}< br/> Public String getsex () {<br/> return sex; <br/>}< br/> Public String getname () {<br/> return name; <br/>}< br/> Public int getage () {<br/> return age; <br/>}< br/> Public String getphone () {<br/> return phone; <br/>}< br/>}
Then write the XML test class. I name this class xmltest. To read and write XML files, you need to import the following Java package
Import java. io. *; <br/> // Java basic package, including various IO Operations <br/> import java. util. *; <br/> // Java basic package, including various standard data structure Operations <br/> import javax. xml. parsers. *; <br/> // XML Parser interface <br/> import org. w3c. dom. *; <br/> // DOM Implementation of XML <br/> import org. apache. crimson. tree. xmlDocument; <br/> // 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 {<br/> // prepare for parsing XML. <br/> Create a DocumentBuilderFactory instance and specify DocumentBuilder <br/> DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); <br/> DocumentBuilder db = null; <br/> try {<br/> db = dbf. newDocumentBuilder (); <br/>} catch (ParserConfigurationException pce) {<br/> System. err. println (pce); <br/> // output exception information when an exception occurs, and then exit. <br/> System. exit (1); <br/>}< br/> Document doc = null; <br/> try {<br/> doc = db. parse (inFile); <br/>} catch (DOMException dom) {<br/> System. err. println (dom. getMessage (); <br/> System. exit (1); <br/>}catch (IOException ioe) {<br/> System. err. println (ioe); <br/> System. exit (1); <br/>}< br/> // the whole process of XML parsing is as follows. <br/> it is relatively simple, first take the root Element "student roster" <br/> Element root = doc. getDocumentElement (); <br/> // obtain the "student" element list <br/> NodeList students = root. getElementsByTagName ("student"); <br/> for (int I = 0; I <students. getLength (); I ++) {<br/> // obtain each "student" Element in sequence <br/> Element student = (Element) students. item (I); <br/> // create a student's Bean instance <br/> StudentBean studentBean = new StudentBean (); <br/> // obtain the student's Gender attribute <br/> studentBean. setSex (student. getAttribute ("gender"); <br/> // obtain the "name" element, which is similar to <br/> NodeList names = student. getElementsByTagName ("name"); <br/> if (names. getLength () = 1) {<br/> Element e = (Element) names. item (0); <br/> Text t = (Text) e. getFirstChild (); <br/> studentBean. setName (t. getNodeValue (); <br/>}</p> <p> NodeList ages = student. getElementsByTagName ("Age"); <br/> if (ages. getLength () = 1) {<br/> Element e = (Element) ages. item (0); <br/> Text t = (Text) e. getFirstChild (); <br/> studentBean. setAge (Integer. parseInt (t. getNodeValue (); <br/>}</p> <p> NodeList phones = student. getElementsByTagName ("phone"); <br/> if (phones. getLength () = 1) {<br/> Element e = (Element) phones. item (0); <br/> Text t = (Text) e. getFirstChild (); <br/> studentBean. setPhone (t. getNodeValue (); <br/>}</p> <p> student_Vector.add (studentBean ); <br/>}</p> <p> private void writeXMLFile (String outFile) throws Exception {<br/> // prepare for parsing XML, <br/> Create a DocumentBuilderFactory instance and specify DocumentBuilder <br/> DocumentBuilderFactory dbf = DocumentBuilderFactory. newInstance (); <br/> DocumentBuilder db = null; <br/> try {<br/> db = dbf. newDocumentBuilder (); <br/>} catch (ParserConfigurationException pce) {<br/> System. err. println (pce); <br/> System. exit (1); <br/>}</p> <p> Document doc = null; <br/> doc = db. newDocument (); </p> <p> // the process of creating XML document content is as follows, <br/> Create the root Element "student roster" <br/> Element root = doc. createElement ("student roster"); <br/> // Add the preceding document to the root element <br/> doc. appendChild (root); </p> <p> // list of beans for retrieving Student Information <br/> for (int I = 0; I <student_Vector.size (); I ++) {<br/> // obtain the information of each student in sequence <br/> StudentBean studentBean = (StudentBean) student_Vector.get (I ); <br/> // create a "student" Element and add it to the root Element <br/> Element student = doc. createElement ("student"); <br/> student. setAttribute ("gender", studentBean. getSex (); <br/> root. appendChild (student); <br/> // create a "name" Element and add it to the student. <br/> Element name = doc. createElement ("name"); <br/> student. appendChild (name); <br/> Text tName = doc. createTextNode (studentBean. getName (); <br/> name. appendChild (tName); </p> <p> Element age = doc. createElement ("Age"); <br/> student. appendChild (age); <br/> Text tAge = doc. createTextNode (String. valueOf (studentBean. getAge (); <br/> age. appendChild (tAge); </p> <p> Element phone = doc. createElement ("phone"); <br/> student. appendChild (phone); <br/> Text tPhone = doc. createTextNode (studentBean. getPhone (); <br/> phone. appendChild (tPhone); <br/>}< br/> // output the XML file to the specified file <br/> FileOutputStream outStream = new FileOutputStream (outFile ); <br/> OutputStreamWriter outWriter = new OutputStreamWriter (outStream); <br/> (XmlDocument) doc ). write (outWriter, "GB2312"); <br/> outWriter. close (); <br/> outStream. close (); <br/>}</p> <p> Add the test main function as follows: <br/> public static void main (String [] args) throws Exception {<br/> // create a test instance <br/> XMLTest xmlTest = new XMLTest (); <br/> // initialize the vector list <br/> xmlTest. student_Vector = new Vector (); </p> <p> System. out. println ("start to read Input. xml file "); <br/> xmlTest. readXMLFile ("Input. xml "); </p> <p> System. out. println ("read finished, start to write Output. xml file "); <br/> xmlTest. writeXMLFile ("Output. xml "); <br/> System. out. println ("Write completed"); <br/>}
Well, save studentbean and xmltest, and save input. XML to the working directory. You can see that "writing is complete.
After reading: this is an article I learned about XML parsing in the early days. In fact, there is nothing to do with parsing XML in Java. I just need to refer to it in time, when XML is too long, you should still consider using Sax for parsing. Dom maps the entire file to the memory, which is too large to sell.