Javase Learning Notes XML parsing technology (5)

Source: Internet
Author: User
Tags xml parser

JAXP Technology

JAXP, the Java API for XML processing, is primarily a complete set of solutions that Sun provides to parse XML data, including DOM and sax parsing techniques. You can refer to Sun's following two packages:

Javax.xml.parsers.*à is the main store of the parser

Org.w3c.dom.* or Org.w3c.sax.*à primarily stores the API required for DOM parsing or sax parsing

Dom parsing mainly uses the DOM tree method to parse the XML data. For example: DOM manipulation in JavaScript

Sax parsing mainly uses the way of event to parse XML data. Such as: The event mechanism in JavaScript

The principle of XML parsing
    1. Write an XML file that needs to be parsed
    2. Get the corresponding XML parser object
    3. Using the API to get data
    4. Return data to the developer
Dom parsing

Dom parsing takes the form of a DOM tree to parse.

    1. Prepare to parse the User.xml file
 <?xml version= 1.0   " Encoding="  utf-8   "?><!--1 . Write the XML file to parse--><users></users> 
 2   //  2. Provides a way to get the parser  public  static   Documentbuilder Getparser () throws exception{ //  2.1 Create factory        Class object  documentbuilderfactory factory = Documentbuilderfactory.newinstance ();  //  2.2 Get parser object  Documentbuilde        R parser = Factory.newdocumentbuilder ();     return   parser; }
3 . Gets the parsed Dom tree object // 3. Provides a way to get DOM data public    static  Document getdom (file file) throws exception{         ///  3.1 Get parser        documentbuilder parser = getparser ();         // 3.2 parsing Data        Document dom = parser.parse (file);         return dom;    }
4. Get the root element//4. Provide a way to parse the root element's data     Public Static voidgetroot (File file) throws exception{//4.1 Getting the DOM treeDocument dom =getdom (file); //4.2 Traversing the DOM tree to find the root elementNode node = dom.getelementsbytagname ("Users"). Item (0); //4.3 The name of the output root elementSystem. out. println (Node.getnodename ()); }
5. Get the root element from a relationship//4. Provide a way to parse the root element's data     Public Static voidgetroot (File file) throws exception{//4.1 Getting the DOM treeDocument dom =getdom (file); //4.2 Traversing the DOM tree to find the root elementNode node = dom.getelementsbytagname ("Users"). Item (0); //4.3 The name of the output root elementSystem. out. println (Node.getnodename ()); //4.4 Get the root element based on the direct relationship of the nodeNodeList list =dom.getchildnodes (); Node Root= List.item (0); System. out. println (Root.getnodename ()); Root=Dom.getfirstchild (); System. out. println (Root.getnodename ()); Root=Dom.getlastchild (); System. out. println (Root.getnodename ()); }
6. Adding elements//5. Add a user node     Public StaticDocument addelement (file file) throws exception{//5.1 Getting the DOM treeDocument dom =getdom (file); //5.2 Creating a user elementElement user = Dom.createelement ("User"); Element name= Dom.createelement ("name"); Element Age= Dom.createelement (" Age"); Element Address= Dom.createelement ("Address"); Name.settextcontent ("Jiao Ningbo"); Age.settextcontent (" -"); Address.settextcontent ("Tianhe District"); //5.3 Building RelationshipsElement root =(Element) dom.getfirstchild ();        User.appendchild (name);        User.appendchild (age);        User.appendchild (address);        Root.appendchild (user); //5.4 Returns the modified DOM tree object        returnDom; }
7in order for the modified DOM tree in memory to persist to a disk file, you need to define the following methods//provides a tool method to store the in-memory DOM tree in a specified file on disk     Public Static voidwritedom2xml (Document dom,file File) throws exception{//1. Get the factory class object for the converterTransformerfactory factory =transformerfactory.newinstance (); //2. Get the Converter objectTransformer trans =Factory.newtransformer (); //3. ConversionTrans.transform (NewDomsource (DOM),NewStreamresult (Newfileoutputstream (file)); }
8. modifying elements//6. Change the age of the second user to 30 years     Public StaticDocument modifyelement (file file) throws exception{//6.1 Getting the DOM treeDocument dom =getdom (file); //6.2 Getting a second Age elementNode Age2 = Dom.getelementsbytagname (" Age"). Item (1); //6.3 Setting text valuesAge2.settextcontent (" -"); returnDom; }
9. Deleting an element//7. Delete the first user node     Public StaticDocument removeelement (file file) throws exception{//7.1 Getting the DOM treeDocument dom =getdom (file); //7.2 Getting the father of the userNode users =Dom.getfirstchild (); //7.2 Getting child nodes that need to sever relationshipsNode user1 = Dom.getelementsbytagname ("User"). Item (0); //7.3 Severance of relationsUsers.removechild (user1); returnDom
Ten. Enhance the use of relationships to get elements//8. Using relationships to get nodes     Public Static voidsearchelement (File file) throws exception{//8.1 Getting the DOM treeDocument dom =getdom (file); //8.2 Gets all the child elements of the second user and enters the element nameElement user2 = (element) Dom.getelementsbytagname ("User"). Item (1); //8.3 Get all the sonsNodeList list =user2.getchildnodes (); //8.4 Traversing all the children         for(inti =0; I<list.getlength (); i++) {node node=List.item (i); System. out. println (Node.getnodename ()); }        //8.5 Get the Address element for the second userElement address2 = (element) List.item (2); System. out. println (Address2.getnodename ()); Node Age2=address2.getprevioussibling (); System. out. println (Age2.getnodename ()); Element name2= (Element) List.item (0); System. out. println (Name2.getnodename ()); Age2=name2.getnextsibling (); System. out. println (Age2.getnodename ()); }
 Oneoperation of the. Property//9. Property Manipulation     Public StaticDocument optionattribute (file file) throws exception{//9.1 Getting the DOM treeDocument dom =getdom (file); //9.2 Getting all the user elementsNodeList list = Dom.getelementsbytagname ("User"); //9.3 Traversing a node         for(inti =0; I < list.getlength (); i++) {Element user=(Element) List.item (i); //Add PropertyUser.setattribute ("ID","xx"+ (i+1)); }        //9.4 Getting PropertiesElement user2 = (element) List.item (1); String value= User2.getattribute ("ID"); System. out. println (value); //9.5 Modifying PropertiesUser2.setattribute ("ID","007"); //9.5 Deleting attributesUser2.removeattribute ("ID"); returnDom; } Summary: In the actual project development we often encounter the XML data is relatively large, if using the DOM for data parsing, then first in memory will form a DOM tree structure. Therefore, it is easy to cause an overflow of memory. Therefore, it is not recommended that you use DOM parsing to manipulate large XML data. Sax parsing is recommended if only data acquisition of the XML file is required. 

Javase Learning Notes XML parsing technology (5)

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.