XML's Java resolution, (2) (1)

zhaozj2021-02-17  55

Java World Copyright Notice: "Mapping Java TO XML, Part 2," by Robert Hustead Was Originally Published Byjavaworld (www.javaworld.com), Copyright IDG, August 2002. Reprinted WithMISSION.

XML's Java resolution, (2)

Create a class library that maps XML documents for the SAX API

This article discusses the development of a SAX API-based class library that can be easily developed to develop XML-Java mapping code. First we explore important ideas regarding this class library demand. A basic class library implementation is then given and several examples involving advanced topics in XML in XML in the SAX API. (2,500 words)

Robert Hustead

As I said in (1), several issues encountered when using the SAX API are only conceptual. I want to emphasize this again because it is the basic issue of the reusable class library developed in this article.

Whether you use DOM or SAX, you have two things happen when you map XML data to Java objects - data navigation and data collection. Dom and SAX have different things in how to achieve these two things. That is, the DOM lets data navigation and data collection are separated, while SAX combines data navigation and data together.

Dom exists in performance mainly comes from the desired separation and DOM programming mode for navigation and data collection, but in fact, this separation is not a ruuntary requirement. SAX sacrifices the intuitiveness of the programming mode, and the data navigation and data collection are all reflected in this concept.

With DOM, after you build in-Memory Dom Tree, you can point to the data node of interest. Then, once you find the correct node, you can collect data. You navigate and collect data like this, which is conceptually isolated. Unfortunately, as I mentioned earlier, using the inline DOM tree means that it is a great discount.

For SAX, this is more like playing a complex trick. You listen to the SAX event and track the location of your own - alternative navigation. When the SAX event pointed you to the correct location, you start collecting data. One of SAX does not occupy the dominant position in the XML API is that it is not as intuitive as DOM in its programming mode.

So, if we can keep SAX's performance in runtime performance and separate data navigation and data collection, isn't it very cool? Ok, pay attention, because this is exactly what we have to do. That is, there is no reason not to separate the navigation and data collection in the design period and make them mix them in the running period.

You are here (English Original "You are here", I check the information that this may be the term on the US road sign, which is equivalent to the "Your location" next to the smile sign on the campus map of Chongqing, use it here Navigation ", translation) In (1), I used some basic SAX programs. I also mentioned some situations that need special attention, such as recursive data structures. To create a class library that separates SAX navigation features in programming, we need a general solution for navigation. This program should be able to cope with all situations, including shared tag names and recursive data structures.

So how do we do it?

The key to navigation in SAX parsing: track the current location of the parsed process at any time. The most complex navigation situation is to follow the SAX events generated by the recursive structure when parsing an XML document tracking the current location. Traditional recursive structural solutions - Sometimes the traversal of trees - is a stack data structure or by calling a recursive function. Unfortunately, because we have to counter the XML parser after processing each SAX event, we cannot use the recursive function. But we can use the stack data structure to track the location where the SAX event occurs. The stack also solved the second question I mentioned in the previous article: If you have a shared label name, such as a label appears multiple times in an XML document, you need to remove this mix. This problem is solved with XML full path from XML root node to shared tag. With the stack, the full path from the root node to the label name is available at any time. In this way, the two special cases are solved with a stack.

For explanation, let's look at an example, this example will put them up after finding the tag and use this string to simulate the stack:

Import org.xml.sax. *; import org.xml.sax.helpers. *; import java.io. *; import java.util. *; import common. *; public class example1 extends defaulthandler {// used to track tracking The currently open label name stack // (so-called "startelement" but does not include "endelement") private stack tagstack = new stack (); // The local vector table of the item name. . . Private vector items = new vector (); // customer name. . . Private string custom000; // is used to collect the cache of data from the "Characters" SAX event. Private CharRaywriter Contents = New CharaRrayWriter (); // Reserved the method of the DefaultHandler class to intercept the SAX event. // / / For details on all effective events, see Org.xml.sax.contenthandler.

// Public void StartElement (String Namespaceuri, String LocalName, string qname, attributes attr) throws saxexception {contents.reset (); // Label Name Add the stack. . . Tagstack.push (localname); // Displays the found current path. . . System.out.println ( "path found: [" getTagPath () "]");.} Public void endElement (String namespaceURI, String localName, String qName) throws SAXException {if (getTagPath () equals ( "/ CustomerOrder / CUSTOMER / NAME ") {Customer = Contents.toString (). Trim ();} else if (" / customerorder / items / item / name ") {items.addeElement (Contents.Tostring () .trim ());} // Clear the stack. . . Tagstack.pop ();} public void character, intlength "," SAXEXCEPTION {// collects content into a cache Contents.Write (ch, start, length);} // from the stack Current status to establish a path string. . . // // efficiency is very low, but we will be discussed later. . . Private string gettagpath () {// Create a path string. . . String buffer = ""; Enumeration E = tagstack.elements (); while (E.hasMoreElements ()) {buffer = buffer "/" (String) E.NEXTELEMENT ();} return buffer;} public vector GetItems ) {RETURN ITEMS;} public string getcustomername () {return customer;} public static void main (String [] argv) {system.out.println ("eXample1:"); try {// Create a SAX 2 parser. . . XmlReader XR =

XmlReaderFactory.createxmlReader (); // Install ContentHandler. . . EXAMPLE1 EX1 = New Example1 (); Xr.SetContentHandler (ex1); system.out.println (); system.out.println ("tag paths locate); // parsing files. . . Xr.Pars (New FileRead (New FileRead))); System.out.Println (); System.out.Println ("Names Located:"); // Display Customer System.Out.println (NAMER SYSTEM.Println "Customer Name:" ex1.getCustomerName ()); // Display all of the order items to the standard output. . . System.out.println ("ORDER ITEMS:"); String Items = EX1.GETITEMS (); ENUMERATION E = Items.Elements (); while (E.hasMoreElements ()) {itemName = (String) E. NEXTELEMENT (); system.out.println (itemname);}} catch (exception e) {E.PrintStackTrace ();}}} The following is the sample data to be used by our example:

Customer x

unknown 098 Item 1 32.01 4093 item 2 0.76 543 Item 3 1.42 with sample data running a case Generate the output below:

Example1: Tag paths located: path found: [/ CustomerOrder] path found: [/ CustomerOrder / Customer] path found: [/ CustomerOrder / Customer / Name] path found: [/ CustomerOrder / Customer / Address] path found: [/ CustomerOrder / Items] Path Found: [/ CustomerORDER / ITEMS / ITEM] Path Found: [/ CustomerORDER / ITEMS / ITEM / ProductCode] Path Found: [/ CustomerORDER / ITEMS / ITEM / Name] Path Found: [/ CustomerORDER / ITEMS / ITEM / Price] path Found: [/ CustomerORDER / ITEMS / ITEM] Path Found: [/ CustomerORDER / ITEMS / ITEM / ProductCode] Path Found: [/ CustomerOrder / items / item / name] Path Found: [/ CustomerOrder / items / item / Price] path Found: [/ CustomerORDER / ITEMS / ITEM] Path Found: [/ CustomerORDER / ITEMS / ITEM / ProductCode] Path Found: [/ CustomerOrder / items / item / name] Path Found: [/ CustomerOrder / items / item / Price] Names Located: Customer Name: Customer Xorder Items: Item 1Item 2Item 3 (unreasonable)

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

New Post(0)