Introduction to using SAX (1)

Source: Internet
Author: User
Tags processing instruction

Introduction to using SAX (1)

Example Sam. xml

<?xml version="1.0" encoding="UTF-8"?><session>   <committee type="monetary">       <title>Finance</title>       <number>17</number>       <subject>Donut Costs</subject>       <date>7/15/2005</date>       <attendees>           <senator status="present">               <firstName>Thomas</firstName>               <lastName>Smith</lastName>           </senator>           <senator status="absent">               <firstName>Frank</firstName>               <lastName>McCoy</lastName>           </senator>           <senator status="present">               <firstName>Jay</firstName>               <lastName>Jones</lastName>           </senator>       </attendees>   </committee></session>
 

Let's write a program, read the XML file, and print it on the console.

Source file:

Import Java. io. *; import Org. XML. sax. *; import javax. XML. parsers. *; import Org. XML. sax. helpers. defaulthandler; public class ch17_02 extends defaulthandler {static? Int numberlines = 0; static? String indentation = ""; static? String displaytext [] = new? String [1000]; // The program starts to execute the main method and calls childloop. childloop fills in a character array displaytext and records the number of strings to numberlines. After the childloop is executed, you only need to print the displaytext content of the array to achieve the program goal. Public? Static void main (string ARGs []) {ch17_02 parser = new ch17_02 (); parser. childloop (ARGs [0]); For (INT loopindex = 0; loopindex <numberlines; loopindex ++) {system. out. println (displaytext [loopindex]);} public void childloop (string URI) {// The first step is to create a defaulthandler // defaulthandler. It tells sax that the object should be called to handle various types of nodes, because our class // ch17_02 extends defaulthandler, in addition, the Program for processing various nodes is provided in the class, so the class itself // is used for processing. Here, the Java keyword "this" indicates If another class such as mysaxhandler is used for processing, it should be // defaulthandler saxhandler = mysaxhandler (); defaulthandler saxhandler = This; // A saxparserfactory object needs to be created in step 2, this is explained in XML by using the sax method. Remember to do so, you can use saxparserfactory saxfactory = saxparserfactory. newinstance (); // create a saxparser in step 3 to interpret XML. This is also a general rule. Call the newsaxparser () method of saxfactory to create a saxparser object, for other common methods of saxfactory, see [common methods of saxfactory] Try {saxparser = saxfactory. Newsaxparser (); // here we can see that the defaulthandler we just created is used to start the explanation of the XML file by calling the parse method of saxparser. // we can see that, explain how to call saxhandler (the defaulthandler we just created) to respond to various events of // sax through the file specified by the command line. For other common methods of saxparser, see [common methods for saxparser]. Saxparser. parse (new file (URI), saxhandler);} catch (throwable t) {}} // The next step is to respond to some events of the sax, because our extends defaulthandler class, therefore, the methods that respond to the sax event are directly written into the class. As we mentioned earlier, if we plan to use mysaxhandler for processing, the following methods appear in // mysaxhandler, of course, our mysaxhandler also needs extends defaulthandler. // Some of the following methods are pre-defined in defaulthandler to correspond to different sax events, for common defaulthandler methods, see [defaulthandler common methods] // when the startdocument method is the defaulthandler method, it indicates that it has started to process a document. // because the purpose of this program is to print a complete XML file, we will add the XML file header here. Public void startdocument () {displaytext [numberlines] = indentation; displaytext [numberlines] + ="
 "1.0/" encoding =/"" + "UTF-8" + "/"?> "; Numberlines ++;} // This method has not been understood yet! // We can handle processing instructions by using the defaulthandler processinginstruction method, // which is called automatically when the SAX Parser finds a processing instruction. the target of // The Processing Instruction is passed to us, as is the data for the processing instruction, which // means you can handle processing instructions like this public void processinginstruction (string target, string data) {displaytext [numberlines] = indentation; displaytext [numberlines] + ="
 ; Displaytext [numberlines] + = target; If (Data! = NULL & Data. Length ()> 0) {displaytext [numberlines] + = ''; displaytext [numberlines] + = data;} displaytext [numberlines] + ="?> "; Numberlines ++;} // startelement is the method in defaulthandler. This method will be called when Sax encounters an element (node). // in case of a node
 "Oracle">, where database is the node name, type = "oracle" is the node property // This method passes some parameters, here we are mainly concerned with qualifiedname (node name ), attributes (node attribute set) // if we want to find a node named database and process its attribute values, as long as if (qualifiedname = "Database ") // you can find the public void startelement (string Uri, string localname, string qualifiedname, attributes) {displaytext [numberlines] = indentation; indentation + = ""; displaytext [numberlines] + = '<'; displaytext [numberlines] + = Qualifiedname; // If an attribute exists, an attributes object is passed. We can interpret this object to obtain all attributes. // various attributes methods, see [common attributes methods] If (attributes! = NULL) {int numberattributes = attributes. getlength (); // call this method to obtain the number of attributes for (INT loopindex = 0; loopindex <numberattributes; loopindex ++) {displaytext [numberlines] + = ''; displaytext [numberlines] + = attributes. getqname (loopindex); // call this method to obtain the attribute name displaytext [numberlines] + = "=/" "; displaytext [numberlines] + = attributes. getvalue (loopindex); // call this method to obtain the attribute value displaytext [numberlines] + = '"';} displayte XT [numberlines] + = '>'; numberlines ++;} // when a text node is encountered, Sax calls the characters method. What is a text node? // Example
 Sa is a text node in SA. Public void characters (char characters [], int start, int length) {string characterdata = (new? String (characters, start, length )). trim (); If (characterdata. indexof ("/N") <0 & characterdata. length ()> 0) {displaytext [numberlines] = indentation; displaytext [numberlines] + = characterdata; numberlines ++ ;}} public void ignorablewhitespace (char characters [], int start, int length) {// characters (characters, start, length);} // The end of a node, such as public void endelement (string Uri, string localname, STR Ing qualifiedname) {indentation = indentation. substring (0, indentation. length ()-4); displaytext [numberlines] = indentation; displaytext [numberlines] + = "; displaytext [numberlines] + = qualifiedname; displaytext [numberlines] + = '> '; numberlines ++;} // The following three methods are used to process errors and warnings. This is also stipulated when using sax. If you write your own // saxhandler, you also need to reload these three methods. Public void warning (saxparseexception exception) {system. err. println ("Warning:" + exception. getmessage ();} public void error (saxparseexception exception) {system. err. println ("error:" + exception. getmessage ();} public void fatalError (saxparseexception exception) {system. err. println ("Fatal error:" + exception. getmessage ());}}

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.