I just saw a microblog.
Today, there are still 2009 days before the countdown to the 100-level school departure
I used the phrase "I did not expect it" in the "Three Kingdoms Kill ". The four years have never imagined that it will soon be gone. Unexpectedly.
There are a lot of complicated things, even though there are no classes near the graduation season. Work, graduation design, thesis, internship report ...... Looking for a job alone will make the job worse. This is why the blog has not been updated for a long time. This is an answer to the interviewer of a company.
After all, the technicians talk about technology. Due to the graduation design, you need to write a Java parsing XML file. (Speaking of graduation design, I think of my teammates. I am working alone in a group of three. Pitfalls ......) The following describes how to parse XML using Java.
Glossary
XML is explained in Wikipedia in this way (everyone knows what it is, so I don't have to go into it)
Extensible Markup Language(English:EXTensibleMArkupLAnguage(Abbreviation:XML), IsMarkup Language.
Java parses XML in many ways. Pull is useful and sax is useful. Here we share the most primitive, Which is parsed by Dom. Let's talk about other things in another day.
What is Dom?
Dom, full name: Document Object Model, that is, "Document Object Model ".
Dom is an XML document object model that can be used to directly access all parts of an XML document. In the Dom, the document is simulated as a tree. Each component of the XML syntax represents a node. The Dom allows users to traverse the document tree and move from the parent node to the child node and the sibling node.
XML original file
First, you can place an XML file on the server, which looks cool.
View code XML file
<? XML version = "1.0" encoding = "UTF-8" ?> < Students > < Student ID = "1" > < Name > Zhang San </ Name > < Phoneno > 621380 </ Phoneno > < Login > True </ Login > </ Student > < Student ID = "1" > < Name > Li Si </ Name > < Phoneno > 641234 </ Phoneno > < Login > True </ Login > </ Student > < Student ID = "1" > < Name > Wang Wu </ Name > < Phoneno > 67890 </ Phoneno > < Login > False </ Login > </ Student > </ Students >
I put the student. xml file on IIS on my machine. You can access http: // localhost/student. XML in the browser.
Object
Create a Class Based on the XML data and type. The class members correspond to the XML attributes, and generate the get and set methods and the tostring () of the class for the class members () to display the results. The following is an instance:
View code Student Class
Package Com. xml. domain; Public Class Student { Private Int ID; Private String name; Private String phone; Public Int GETID (){ Return ID ;} Public Void Setid ( Int ID ){ This . ID = ID ;} Public String getname (){ Return Name ;} Public Void Setname (string name ){ This . Name = Name ;} Public String getphone (){ Return Phone ;} Public Void Setphone (string phone ){ This . Phone = Phone ;} Public Boolean Islogin (){ Return Login ;} Public Void Setlogin (Boolean Login ){ This . Login = Login ;} Private Boolean Login; @ override Public String tostring (){ Return "Student [ID =" + ID + ", name =" + name + ", phone =" + Phone + ", Login =" + login + "]" ;}} Resolution Method
Create a new class (My use case creates a domservice class) and write a method for parsing XML files in the class. This method uses DOM technology to parse data and convert XML files into a list set. For details, seeCode.
1 // Convert XML into an object 2 Public List <student> getstudents (inputstream) Throws Exception { 3 List <student> List = New Arraylist <student> (); 4 // Create a document resolution Factory 5 Documentbuilderfactory factory = Documentbuilderfactory. newinstance (); 6 Documentbuilder builder = Factory. newdocumentbuilder (); 7 // Parses the input stream into a document 8 Document document = Builder. parse (inputstream ); 9 // The entire document is a node document, so this node is all content. 10 Element ele = Document. getdocumentelement (); 11 Nodelist = ELE. getelementsbytagname ("student "); // Obtain and traverse all student nodes 12 For ( Int I = 0; I <nodelist. getlength (); I ++ ){ 13 Element ele2 = (element) nodelist. item (I ); // A specific student Node 14 Student = New Student (); 15 Student. setid (integer. parseint (ele2.getattribute ("ID" ))); 16 // Obtain and traverse all subnodes under the Student Node 17 Nodelist nodelist2 = Ele2.getchildnodes (); 18 For ( Int J = 0; j <nodelist2.getlength (); j ++ ){ 19 If (Nodelist2.item (j). getnodetype () = node. element_node ){ // If this node is an element node 20 If ("Name" . Equals (nodelist2.item (j). getnodename ())){ 21 Student. setname (nodelist2.item (j). getfirstchild () 22 . Getnodevalue ()); 23 } Else If ("Phoneno" . Equals (nodelist2.item (j). getnodename ())){ 24 Student. setphone (nodelist2.item (j). getfirstchild () 25 . Getnodevalue ()); 26 } Else If ("Login" . Equals (nodelist2.item (j). getnodename ())){ 27 Student. setlogin (Boolean. parseboolean (nodelist2.item (j) 28 . Getfirstchild (). getnodevalue ())); 29 } 30 } 31 } 32 List. Add (student ); // Add to set 33 } 34 Return List; 35 }
Dom parsing requires coding based on the specific XML structure. In general, it is flexible and easy to understand. However, if the XML file depth is large, the DOM parsing efficiency will be greatly reduced. Because Dom parsing loops with depth, the efficiency of multiple loops is not high. So it is not very recommended, especially when XML is very deep.
HTTP Request
Since I put XML on the server, I will also talk about how to use Java code to obtain XML files. I wrote the following method.
View code HTTP Request Method
// PATH is the address path // The returned value is returned as a stream. Public Static Inputstream getxml (string path) {inputstream = Null ; Try {URL = New URL (PATH ); If (URL! = Null ) {Httpurlconnection connection = (Httpurlconnection) URL. openconnection (); connection. setconnecttimeout ( 3000 ); // Set the timeout value to 3 seconds. Connection. setdoinput ( True ); Connection. setrequestmethod ( "Get "); // Set Request Method Int Code = connection. getresponsecode (); // Accept return code If (200 = Code ){ // The return code 200 indicates that the request is successful. Inputstream = Connection. getinputstream ();}}} Catch (Exception e ){ // Todo auto-generated Catch Block E. printstacktrace ();} Return Inputstream ;}
Next we can make XML requests to the server and parse the XML.
Test Results
Compile in the main method
Public Static Void Main (string [] ARGs ){ // Todo auto-generated method stub String path = "Http: // localhost/student. xml" ; Inputstream Input = Httputils. getxml (PATH); domservice Service = New Domservice (); Try {List <Student> List = Service. getstudents (input ); For (Student: List) {system. Out. println (student. tostring ());}} Catch (Exception e ){ // Todo auto-generated Catch Block E. printstacktrace ();}}
Publish the code and get the result.
Student [ID = 1, name = Michael, phone = 621380, login = true]
Student [ID = 1, name = Li Si, phone = 641234, login = true]
Student [ID = 1, name = Wang Wu, phone = 67890, login = false]
Full project code download: http://vdisk.weibo.com/s/uIkgX
------ I am bored with the split line -------
The above is the process of learning Dom parsing and data transmission. I hope it will help you.