XML Java Analysis (1) (2)

zhaozj2021-02-17  67

Hello World Now we understand the basic SAX principle, we can do a little useful: parsing the value from our XML sample document to implement classic Hello World programs.

First, an element of interest is primarily in Java, and we reset our data cache at the StartElement event. Then, when STARTELEMENT has occurred, the endelement event has not yet, we collect all characters corresponding to the CHARACTERS event. Finally, when the endelement event appears, we save the collected characters to the corresponding attribute of a Java object.

The following is the sample data used by our Hello World:

// public void startElement (String namespaceURI, String localName, String qName, Attributes attr) throws SAXException {contents.reset ();} public void endElement (String namespaceURI, String localName, String qName) throws SAXException {if (localName.equals ( "name")) {name = contents.tostring ();} if (localname.equals ("location")) {location = contents.tostring ();}} public void characters (char [] ch, int Start, int start, int Length) THROWS SAXEXCEPTION {Contents.write (CH, START, LENGTH);} public static void main (string [] argv) {system.out.println ("eXample2:"); try {// Create a SAX 2 parser. . . XmlReader XR = XmlReaderFactory.createxmlReader (); // Install ContentHandler. . . Example2 ex2 = new example2 (); xr.setContentHandler (ex2); // parsing files. . . Xr.Parse (New FileRead (New FileRead ("Example2.xml"))); // Say Hello ... System.Out.println ("Hello World from" EX2.NAME "in" ex2.location) ;} Catch (exception e) {E.PrintStackTrace ();}}} Our Hello World example output is as follows:

Example2: Hello World from Bob in New York

This is not the simplest in all Hello World programs. Similarly, there are several cases in this example code that is not perfect.

First, this code shows some of the shortcomings of the event-driven code. When an event-driven program is not to respond to an event, things should be responding to a class of events. Take the above code as an example, we are looking for a class of events that appear in the name and in the XML sample document.

The content in the tag appears in the Characters SAX event; the label itself is located between the StartElement and endelement events. I use the Contents cache that constantly empties in StartElement to handle them. The emergence of the end label means that the data is collected, saved it to the correct local variable. This is good, but it assumes that there is no two Java objects that use the same label - this assumption is not always right. We have to deal with this problem later. Another interesting feature of this routine is the use of Contents cache - an SAX tips. You can also create a string directly in the Characters SAX event to replace this way to copy the characters into the cache. But this also means that the XML parser pointed out in the SAX document related to Characters () may be called multiple times. This may result in the collection of data between the two tags between the data between the two tags is too large or input to the XML parser is disconnected, and the data is lost. In addition, reusing a cache is much more efficient than constantly creating new objects.

Create our first Java object map Now we have finished Hello World, let us try an example of an XML document to print an XML document to the Java object. This example is similar to Hello World, but it is also necessary to map data into an object and have a caller - this is a very common model in the later example. The objects in the SAX parser in the SAX parser are not intended to constructor and the Factory method. For this loss, a clean land is to create an access control method for objects that have been successfully mapped in the object of mapping objects (translation: also as a field). In this way, you create a mapping class, assign it an XMLReader, parse XML, and then call the access control method to get a reference to the object mapped. An alternative is to provide a SET method that assigns objects of the accommodating data to be resolved before parsing.

Let's take a look at the XML sample documentation:

Bob hustead abc.123

Next, let's take a simple class that will be mapped from our XML document:

Package Common; Import Java.io. *; // Customer is a simple class that contains properties of a virtual customer. // It has a simple way to print from a print flow. public class Customer {// Customer member variables public String firstName = ""; public String lastName = ""; public String custId = ""; public void print (PrintStream out) {out.println ( "Customer:"); out. Println ("First Name ->" FirstName); Out.Println ("Last Name ->" LastName); Out.println ("Customer ID ->" CustId;}}

This is the code of the class in Example 3 to analyze the class:

Import org.xml.sax. *; import org.xml.sax.helpers. *; import java.io. *; import common. *; public class example3 extends defaulthandler {// Local Customer for collector's XML data Variable Private Customer Cust = New Customer (); // Used to collect data from the "Characters" SAX event. Private CharRaywriter Contents = New CharaRrayWriter (); // Reserved the method of the DefaultHandler class to intercept the SAX event. // / / Refer to Org.xml.sax.contenthandler.

// public void startElement (String namespaceURI, String localName, String qName, Attributes attr) throws SAXException {contents.reset ();} public void endElement (String namespaceURI, String localName, String qName) throws SAXException {if (localName.equals ( "Firstname")) {cust.firstname = contents.tostring ();} if (localname.equals ("lastname")) {cust.lastname = contents.tostring ();} if (localname.equals ("custid") ) {Cust.custid = Contents.tostring ();} public void character, int} throws saxception {contents.write (ch, start, length);} public customer getcustomer ()} Return Cust;} public static void main (string [] argv) {system.out.println ("EXAMPLE3:"); try {// Create a SAX 2 parser. . . XmlReader XR = XmlReaderFactory.createxmlReader (); // Install ContentHandler. . . Example3 ex3 = new example3 (); xr.setContentHandler (ex3); // parsing files. . . Xr.Parse (New FileRead (New FileRead ("Example3.xml"))); // Displays Customer to the standard output. . . Customer Cust = EX3.GETCUSTOMER (); Cust.Print (System.out);} catch (exception e) {E.PrintStackTrace ();}}} The following is the output generated by our Customer object, showing from our XML Data of the document:

EXAMPLE3: Customer: First Name -> Bob Last Name -> Hustead Customer ID -> ABC.123 (Unreasonable)

转载请注明原文地址:https://www.9cbs.com/read-30177.html

New Post(0)