Java parsing XML data (using the Jaxp method)

Source: Internet
Author: User
Tags xml parser

There are two main ways to parse XML, one is DOM, and one is sax.

The 1.dom method is to put the XML data into memory as an object in a tree-like structure.

(1) Advantages: Convenient for the data in the XML and other changes, is the recommended way of processing XML data

(2) Disadvantage: This method is not conducive to reading a larger XML file, prone to memory overflow.

2.sax mode is the use of event-driven, edge-reading edge parsing, from the top down, a line of resolution of the way to operate

(1) Advantages: no memory overflow when dealing with larger XML files

(2) Disadvantage: Can not realize the operation of adding and deleting, not the official website standard, but almost all the XML parser support it

3. For the time being, we first select one of the three main parsers to parse the XML data in a JAXP way, the main three parsers are:

(1) Jaxp provided by Sun Corporation

(2) dom4j provided by dom4j organization (max.)

(3) Jdom provided by Jdom organization

Here is the code for adding and deleting XML data: Comments in code

 PackageNg.www.jaxp;Importjava.io.IOException;ImportJavax.xml.parsers.DocumentBuilder;Importjavax.xml.parsers.DocumentBuilderFactory;Importjavax.xml.parsers.ParserConfigurationException;ImportJavax.xml.transform.Transformer;Importjavax.xml.transform.TransformerConfigurationException;Importjavax.xml.transform.TransformerException;Importjavax.xml.transform.TransformerFactory;ImportJavax.xml.transform.dom.DOMSource;ImportJavax.xml.transform.stream.StreamResult;Importorg.w3c.dom.Document;Importorg.w3c.dom.Element;ImportOrg.w3c.dom.Node;Importorg.w3c.dom.NodeList;ImportOrg.w3c.dom.Text;Importorg.xml.sax.SAXException;/*** Implement JAXP operation XML *@authorWangweiwei **/ Public classTESTJAXP {/**     * @paramargs *@throwsparserconfigurationexception *@throwsIOException *@throwssaxexception *@throwstransformerexception*/     Public Static voidMain (string[] args)throwsparserconfigurationexception, Saxexception, IOException, transformerexception {//AddNode (); //Editnode (); //Deletenode (); //Selectsin ();Transervalnode (); //SelectAll ();    }        Private Static voidTranservalnode ()throwsparserconfigurationexception, Saxexception, IOException {/** Here is the node that traverses the XML*/documentbuilderfactory builderfactory=documentbuilderfactory.newinstance (); Documentbuilder Builder=Builderfactory.newdocumentbuilder (); Document Document=builder.parse ("Src/person.xml"); //write a method to implement a traversal operationList1 (document); }        Private Static voidList1 (node node) {if(Node.getnodetype () = =Node.element_node)        {System.out.println (Node.getnodename ()); }        //get a layer of child nodesNodeList nodelist=node.getchildnodes ();  for(intI=0;i<nodelist.getlength (); i++){             //Get each nodeNode node1=Nodelist.item (i);         List1 (Node1); }    }    Private Static voidDeletenode ()throwsparserconfigurationexception, Saxexception, IOException, transformerexception {/** Here is the node that deletes the XML*/documentbuilderfactory builderfactory=documentbuilderfactory.newinstance (); Documentbuilder Builder=Builderfactory.newdocumentbuilder (); Document Document=builder.parse ("Src/person.xml"); //get the Sex elementNode node=document.getelementsbytagname ("Sex"). Item (0); Node parentnode=Node.getparentnode ();        Parentnode.removechild (node); //write back to the local XML fileTransformerfactory factory=transformerfactory.newinstance (); Transformer former=Factory.newtransformer (); Former.transform (NewDomsource (document),NewStreamresult ("Src/person.xml")); }        Private Static voidEditnode ()throwsparserconfigurationexception, Saxexception, IOException, transformerexception {/** Edit XML data (Modify the text data under sex as Nan) * using the Sextextcontent method*/documentbuilderfactory builderfactory=documentbuilderfactory.newinstance (); Documentbuilder Builder=Builderfactory.newdocumentbuilder (); Document Document=builder.parse ("Src/person.xml"); //get the node for sexNode Sexnode = document.getelementsbytagname ("Sex"). Item (0); Sexnode.settextcontent ("Nan"); //The memory has been modified, and now the data in memory needs to be written back to the local XML file before it takes effectTransformerfactory factory=transformerfactory.newinstance (); Transformer former=Factory.newtransformer (); Former.transform (NewDomsource (document),NewStreamresult ("Src/person.xml")); }        Private Static voidAddNode ()throwsparserconfigurationexception, Saxexception, IOException, transformerexception{/** Here the operation needs to write XML, or else just modify the XML data in memory, the local file will not change*/documentbuilderfactory builderfactory=documentbuilderfactory.newinstance (); Documentbuilder Builder=Builderfactory.newdocumentbuilder (); Document Document=builder.parse ("Src/person.xml"); Node Node=document.getelementsbytagname ("P1"). Item (0); Element element=document.createelement ("Sex"); Text text= document.createTextNode ("NV");        Element.appendchild (text);        Node.appendchild (Element); //writes XML data to the localTransformerfactory formerfactory=transformerfactory.newinstance (); Transformer former=Formerfactory.newtransformer (); Former.transform (NewDomsource (document),NewStreamresult ("Src/person.xml")); }        Private Static voidSelectsin ()throwsparserconfigurationexception, saxexception, ioexception{/** 1. Create parser Factory * 2. Create a parser based on the parser factory * 3. Parse XML, return document * 4. Get all the name elements * 5. Take advantage of the returned collection Inside the item (0) to get the first name element * 6. Use the Gettextcontext method to obtain a specific value*/                //Creating a parser factoryDocumentbuilderfactory builderfactory=documentbuilderfactory.newinstance (); //Create a parser based on the parser factoryDocumentbuilder builder=Builderfactory.newdocumentbuilder (); //returns the Document object of XML according to the parserDocument document=builder.parse ("Src/person.xml"); //gets all the name elements according to the document object, and then takes the first element using the item (0)Node node=document.getelementsbytagname ("name"). Item (1); String s=node.gettextcontent ();    System.out.println (s); }        Private Static voidSelectAll ()throwsparserconfigurationexception, Saxexception, IOException {//Query the value of all tags in XML as name        /** 1. Create parser Factory * 2. Create a parser based on the parser factory * 3. Parse XML returns document * 4. Gets all the name elements * 5. Iterate through the collection to get each A name Element*/        //Creating a parser factoryDocumentbuilderfactory builderfactory=documentbuilderfactory.newinstance (); //Creating a parserDocumentbuilder builder=Builderfactory.newdocumentbuilder (); //parsing XML returns documentDocument document= builder.parse ("Src/person.xml"); NodeList List= document.getElementsByTagName ("Sex"); //Traversal Start         for(intI=0;i<list.getlength (); i++) {Node name1=List.item (i); //get the value of the inside element.String nametext=name1.gettextcontent ();        System.out.println (Nametext); }    }}

The XML file that corresponds to the action:

<?XML version= "1.0" encoding= "UTF-8" standalone= "no"?>< Person>    <P1>        <name>Wangweiwei</name>        < Age>23</ Age>        <Sex>Nv</Sex>    </P1>    <P1>        <name>haha</name>        < Age>30</ Age>    </P1></ Person>

Java parsing XML data (using the Jaxp method)

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.