Java XML parsing-How far can we go series (12)

Source: Internet
Author: User
How far can we go series (12)

Nonsense:It's very close to the 15 phases of the series, and the final objectives of the 100 series.

Recently, I received an interview notice and made a written test. Most of them are basic questions, including Java and SQL. It seems that the next job change is about to begin, haha.

I only remember a simple small question. I changed ABC to CBA. It's a simple basic question, but I can't remember any other questions in the pen question. Ah...

Implementation:

 Package  Code. Stu. String;  Public   Class  Inversion {  Public   Static   Void  Main (string [] ARGs) {system. Out. println (inversion ( "Abcdefghijk"));}  Public   Static  String inversion (string Str ){  Char [] Chars = Str. tochararray (); //  String to Char []          Int Len = Chars. length;  Int Min = 0 ;  Int Max = len-1 ;  Char Value;  While (Min <Len/2 | max> Len/2 ){ //  The loop jumps out when the call is in the middle.  //  Three-Step Interchange Value = Chars [Min]; chars [Min] = Chars [Max]; chars [Max] = Value; min ++ ; Max -- ;}  Return String. valueof (chars );//  Char [] to string  }} 

 

Subject:

We are familiar with XML parsing. XML is useful in many aspects, such as spring, tomcat, and ibatis.

This article introduces two methods for parsing XML in Java: Dom and sax.

The DOM method is to read the entire XML file into the memory for parsing.

The method of Sax isRead each node and content step by stepTrigger the event for parsing.

Two TypesCodeThe calling method is as follows: in fact, their source code is worth some effort.

DOM:

 
 
 /**  **  @ Param  Path: Path of the configuration file * @ Param  Nodename node name *  @ Param  Nodevalue to what value *  @ Return  *  @ Throws  Exception  */      Public   Int Changeconfig1 (string path, string nodename, string nodevalue) Throws  Exception {file config = New File (PATH );  //  Parser factory type Documentbuilderfactory DBF = Documentbuilderfactory. newinstance ();  //  Parser Documentbuilder DB = DBF. newdocumentbuilder ();  //  Document Tree Model document Document document = DB. parse (config );  //  A. XML document Parsing Nodelist =Document. getelementsbytagname (nodename );  //  B. Convert the XML document to be parsed into an input stream before parsing.  //  Inputstream is = new fileinputstream (config );  //  Document nodelist = dB. parse (is );          For ( Int I = 0; I <nodelist. getlength (); I ++ ){  //  Element extends Node Element Node =(Element) nodelist. item (I); system. Out. println (node. getelementsbytagname ( "B"). Item (0 ). Getfirstchild (). getnodevalue (); node. getelementsbytagname (nodename). Item ( 0 ). Getfirstchild (). settextcontent (nodevalue); system. Out. println (node. getelementsbytagname ( "C"). Item (0 ). Getfirstchild (). getnodevalue ());}  //  The modification takes effect. Many code on the Internet did not mention this step. I don't know how they modified the XML value.  //  It can be understood that the data in the memory has been changed and has not been mapped to the file. Transformerfactory tffac =Transformerfactory. newinstance (); transformer TF = Tffac. newtransformer (); domsource Source = New  Domsource (document); TF. Transform (source,  New Streamresult (config )); //  Modify content ing to file          Return 0 ;} 
 
 

 

Sax:

 Package  Web. method. file. Sax; Import  Java. Io. filereader;  Import  Java. util. arraylist;  Import  Java. util. List;  Import  Org. xml. Sax. attributes;  Import  Org. xml. Sax. inputsource;  Import  Org. xml. Sax. saxexception;  Import  Org. xml. Sax. xmlreader;  Import Org. xml. Sax. helpers. defaulthandler;  Import  Org. xml. Sax. helpers. xmlreaderfactory;  Import  Web. method. file. model. People;  //  Inherit defaulthandler  Public   Class Confighandler Extends  Defaulthandler {  Private   Final List <people> les = New Arraylist <people> ();  Private  People P;  Private String currentvalue = Null  ;  Private String pretag = Null  ; @ Override  //  Start Element      Public   Void Startelement (string Uri, string localname, string name, attributes)  Throws  Saxexception {  If ("People" . Equals (name) {P = New  People ();} pretag = Name ;}@ override  //  End Element      Public   Void Endelement (string Uri, string localname, string name)  Throws  Saxexception {  If ("People". Equals (name) & P! = Null  ) {Les. Add (p);} pretag = Null  ;} @ Override  //  Value      Public   Void Characters ( Char [] CH,Int Start, Int  Length)  Throws  Saxexception {currentvalue = New  String (CH, start, length );  If (Pretag! = Null & P! = Null  ){  If (Pretag. Equals ("name" ) {P. setname (currentvalue );} Else   If (Pretag. Equals ("from" ) {P. setfrom (currentvalue );}}}  //  Value      Public List <people> Getles les (){  Return  Using LES ;}  Public   Static   Void Main (string [] ARGs) Throws Exception {confighandler Handler = New  Confighandler ();  //  Create an XML Parser (read and parse XML using SAX) Xmlreader reader = Xmlreaderfactory. createxmlreader ();  //  Set the processor for processing document content-related events of the XML Parser  Reader. setcontenthandler (handler );  //  Parse the books. XML document Reader. parse ( New Inputsource (New Filereader ("d :\\ My Documents \ company. xml" )));  For ( Int I = 0; I  ) {System. Out. println (handler. getcmdles (). Get (I). getname ());}}} 

XML:

 <?  XML version = "1.0" encoding = "UTF-8" standalone = "no"  ?>  <  Company  Count  = "3" Xmlns  = "Http://test.org/company"  >    <  People  >  <  Name  > DC </  Name  >  <  Age  > 96 </  Age >  <  From  > Los Angles </  From  >  <  Discription  > Have biggest mind in the world </  Discription  >  </  People  > <  People  >  <  Name  > Jiannanchun </  Name  >  <  Age  > 96 </  Age  >  <  From > Las vages </  From  >  <  Discription  > A good defender </  Discription  >  </  People  >  </  Company  >  

Conclusion: This is just the beginning of XML parsing. Learn how to use it first.

Why should we continue to learn about this? Because when I am idle, I want to compile a project and use XML to store data. If you have learned this, give me some suggestions.

The problem is:How to design a structure for reading XML files with multiple threads? Give suggestions if you have any ideas.

 

Let's move on

----------------------------------------------------------------------

Hard work may fail, but not hard work will certainly fail.
Mutual encouragement.

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.