Java methods for loading and parsing XML files

Source: Internet
Author: User

For Java, there are two ways to load and parse XML files:

One is to generate a document by loading the entire XML file and parse the tree and root of the document content.

Another method is to use the sax encapsulation class for gradual parsing.

The two methods have their own advantages and disadvantages: the first method is to load the entire XML file to generate a document and parse it. Therefore, if the content of the XML file is too large, it will cause loading delay, slow (so this method is only applicable to XML files with relatively small XML files). The second method uses the sax encapsulation class to load XML files to achieve simultaneous loading and parsing, you don't have to wait until all the XML content is loaded, so you don't have to worry about the XML file being too large or too much content. However, the system resources consumed are more than the first one. Therefore, each has its own advantages and disadvantages. In a word, if the XML file is small, the first method is used. If the file is too large, the second method is used.

First, let's take a look at the structure of the entire project.

Gamers. XML is the XML file to be parsed. Let's take a look at the content in XML.

<?xml version="1.0" encoding="UTF-8"?><Gamers>    <Gamer>        <ID>TOR_Apple</ID>        <Grade>13</Grade>    </Gamer>    <Gamer>        <ID>TOR_zhuang</ID>        <Grade>16</Grade>    </Gamer>    <Gamer>        <ID>TOR_KongBai</ID>        <Grade>13</Grade>    </Gamer>    <Gamer>        <ID>TOR_OMG</ID>        <Grade>16</Grade>    </Gamer></Gamers>

XML file structure: Tree <gamer>, root <gamer>, element <ID>, and <Grade> (I am a Warcraft fan ~~).

Now, let's take a look at the first method: Parse XML files by generating a document.

Package COM. parsers; import Java. io. file; import Java. io. ioexception; import javax. XML. parsers. documentbuilder; import javax. XML. parsers. documentbuilderfactory; import javax. XML. parsers. parserconfigurationexception; import Org. w3C. dom. document; import Org. w3C. dom. nodelist; import Org. XML. sax. saxexception; public class xmlparsers {// use Dom resolution form/*** @ Param ARGs */public static void main (string [] ARGs) {// todo Auto-generated method stub // import the XML file. Note that the path of the XML file must be correct file = new file ("xmlfields/gamers. XML ");/* instantiate a documentbuildfactory, a factory built by the document constructor. As the name suggests, I think everyone can guess its role. */Documentbuilderfactory DBF = documentbuilderfactory. newinstance (); documentbuilder dB; try {// instantiate a documentbuilder and a document constructor to generate document DB = DBF. newdocumentbuilder (); // use the parse () method of the constructor to generate a file object to generate the corresponding document = dB. parse (File);/* search for the corresponding root in the document based on the string. the return value is a node linked list. If the linked list does not understand, you can check the data structure */nodelist = document. getelementsbytagname ("gamer"); For (Int J = 0; j <nodelist. getlength (); j ++ ){/ /Return the child nodes in the corresponding root. The returned value is also the node linked list nodelist childlist = nodelist. item (j ). getchildnodes (); For (INT I = 0; I <childlist. getlength (); I ++) {// obtain the name of the element in the corresponding root string tagname = childlist. item (I ). getnodename (); If (tagname. equals ("ID") {/** note that if I want to obtain the value under the ID tag (for example, tor_apple), many people write * childlist. item (I ). getnodevalue (), but this is an error and will not wait for the corresponding result, because childlist. item (I) * The Code only obtains <ID>, while tor_apple is not the value of <ID>, but a subnode of <ID>. Remember */system. out. print (childlist. item (I ). getchildnodes (). item (0 ). getnodevalue () + "=");} else if (tagname. equals ("Grade") {system. out. println (childlist. item (I ). getchildnodes (). item (0 ). getnodevalue () ;}}} catch (parserconfigurationexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (saxexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();}}}

Well, there are comments in the code. I believe everyone will understand it. The first method for parsing XML files is described here. Next, there is the second method to parse XML files.

Package COM. parsers; import Java. io. ioexception; import javax. XML. parsers. parserconfigurationexception; import javax. XML. parsers. saxparser; import javax. XML. parsers. saxparserfactory; import Org. XML. sax. attributes; import Org. XML. sax. inputsource; import Org. XML. sax. saxexception; import Org. XML. sax. helpers. defaulthandler; public class xmlparsersusersax extends defaulthandler {/*** @ Param ARGs */string tagname = NULL; public static void main (string [] ARGs) throws parserconfigurationexception, saxexception, ioexception {// todo auto-generated method stubxmlparsersusersax SPUs = new xmlparsersusersax (); // instantiate a sax parsing factory saxparserfactory SPF = saxparserfactory. newinstance (); // generate a SAX Parser saxparsersaxparser saxparser = SPF through the factory. newsaxparser (); // parse the XML file saxparser. parse (New inputsource ("xmlfields/gamers. XML "), SPUs) ;}@ overri Depublic void startdocument () throws saxexception {// todo auto-generated method stub // automatically called by the system. When parsing XML files (encountering Tree nodes ), system will be automatically called. out. println ("prepare to start parsing the object .... ") ;}@ overridepublic void enddocument () throws saxexception {// todo auto-generated method stub // The system calls it automatically. When the XML file is parsed (the tree End Node is encountered ), system will be automatically called. out. println ("Object Parsing ends .... ") ;}@ overridepublic void startelement (string Uri, string localname, string QNAME, attrib Utes attributes) throws saxexception {// todo auto-generated method stub // the system automatically calls if (QNAME. equals ("ID") | QNAME. equals ("Grade") {system. out. println ("starting to parse elements... "); tagname = QNAME. trim (); system. out. println (tagname) ;}@ overridepublic void endelement (string Uri, string localname, string QNAME) throws saxexception {// todo auto-generated method stub // the system automatically calls system. out. println ("the element is parsed... "); tagname = NULL;} @ over Ridepublic void characters (char [] CH, int start, int length) throws saxexception {// todo auto-generated method stub // the system automatically calls if (tagname! = NULL) {If (tagname. equals ("ID") {system. out. print (tagname + ":" + new string (CH, start, length) + "=");} else if (tagname. equals ("Grade") {system. out. println (tagname + ":" + new string (CH, start, length ));}}}}

Okay. We have finished both methods ~~ Haha, I don't know if it is useful to everyone. I hope you will leave valuable comments after the great friends and gods. Thanks !!!

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.