Overview: eXtensible Markup Language (XML) is being rapidly used in the industry. It has become a widely used standard for describing and exchanging data in a format that is independent of platform, language and protocol. XML and its auxiliary specifications can be used to describe the document representation of data, describe the limitations of XML document types, describe the links between XML documents and resources, and describe the automatic conversion and formatting of XML documents.
How to develop a custom tag library?
I have been using JSP and ASP programming for a long time. Among the two server-side programming methods, I increasingly feel that JSP is much more powerful. Not to mention anything else, the tag library of JSP is the reason why I choose JSP as the preferred server-side web application development tool. Why? Because: speed of maintenance and development. Within a single server page, you can mix and match various script methods and objects. Like "concrete", this mix makes server-side scripting powerful and allows server-side programmers to design very flexible and dynamic Web pages. However, this free mix also has its disadvantages, which is that it is difficult to maintain. Very cumbersome, especially as the project gets larger, since the final product is maintained by a traditional web designer, and even worse, the speed of development increases as the complexity of the code increases. It will become slower and is not conducive to the development of medium and large-scale web applications. Once developed, the site will still need to find qualified programmers to maintain these rather complex codes.
Fortunately, JSP provides a good solution. Tag libraries provide an easy way to build a reusable block of code. Once a tag library is designed, it can be used again in many projects. What's even more convenient is that, unlike COM and J2EE, you don't need to learn any other skills to create a tag library! As long as you know how to write JSP, you can create a tag library. Tag libraries can also improve the maintenance of web applications. This is a simple XML interface thanks to the custom tags of the JSP page. In this way, Web designers can even build JSP Web applications without knowing any JSP knowledge. This open web development is very effective for team operations. JSP programmers can create custom tags and background code modules, while Web designers can use custom tags to build Web applications and focus on Web design.
1. Definition of tag library JSP tag library (also called custom library) can be regarded as a set of methods for generating XML-based scripts, which is supported by JavaBeans. Conceptually, tag libraries are very simple and reusable code constructs.
Tag examples and HTML pages that perform XML/XSL conversion
<%@ taglib uri=" http://www.jspinsider.com/jspkit/JAXP " prefix="JAXP"%>
c:/xml/example.xml
c:/xml/example.xsl
In this example, by using simple tags to access the more powerful code behind the scenes, an XML is loaded and a result is generated through an XSL file and sent to the client, all via This is done using a simple tag call.
Custom tags open the door to creating easily reusable code in JSP projects. All you need is a tag library and its documentation.
2. Tag components Although the tag library is very easy to use, it is quite complicated to create an internal design to support the tag library, at least more complicated than creating a simple JavaBean. The complexity comes from the fact that the tag library is composed of several parts. However, you only need to know Java and JSP.
A simple tag consists of the following elements:
⑴ JavaBeans: In order to obtain the inherent object-oriented benefits of Java, reusable code should be placed in an independent code container. These JavaBeans are not part of the tag library. But it is the basic block of code that your code base uses to perform related tasks.
⑵ Tag processing: This is the real core of the tag library. A tag handler will reference any resources it needs (your JavaBeans) and access all information about your JSP page (the pageContext object). The JSP page will also transmit all the tag attributes that have been set and the contents of the tag body on the JSP page to the tag processor. After the tag processor is finished processing, it will send the output back to your JSP page for processing.
⑶ Tag library description (tld file): This is a simple XML file that records the attributes, information and location of the tag processor. The JSP container uses this file to know where and how to call a tag library.
⑷ Website's web.xml file: This is the initialization file of your website. In this file, you define the custom tags used in the website, and which tld file is used to describe each custom tag.
⑸ Distribution file (a WAR or JAR file): If you want to reuse custom tags, you need a way to transfer it from one project to another. Packaging the tag library into a JAR file is a simple and effective way.
⑹ Make a tag library declaration in your JSP file: It is very simple. If you want to use this tag, just declare it on the page. After that, you can use it anywhere in the JSP page.
It seems like a lot of work to do, but it's actually not that difficult. The point is not about coding, but about organizing the pieces correctly. However, this layering is important because it makes label use flexible and easier to transfer. More importantly, these layers exist to automate the process of creating tags through a JSP IDE (JSP Integrated Development Environment). It is expected that future JSP IDEs can automatically complete most of the work of creating a custom tag, so that you only need to write code and tag processing.
Note: A tag handler defines only one custom tag; a tag library is a collection of several tag processors that handle the same task.
3. Create your own tags. The following will teach you step by step how to create custom tags. The specific example is to extend JSP so that it has its own HTML encoding function. This feature replaces all < and > characters with HTML code. It can be easily extended to do other encoding processing. To simplify, this example only explains the basic elements of creating a custom tag.
⑴ Create a JavaBean
Any reusable part of your code should be placed in a JavaBean. This is important because you will often use this code elsewhere in the project. Any code placed inside a tag handler is not reusable outside of the tag, so it is important to isolate the reusable code portions. In this example, the logic coded for HTML is common and therefore placed in a JavaBean.
⑵ HTML encoding JavaBean
/* HTML_Format.Java */
public class HTML_Format extends Object implements Java.io.Serializable {
/** Create new HTML_Format */
public HTML_Format() {}
/** Replace all < and > characters in a string with the response HTML encoding */
public String HTML_Encode(String as_data)
{
int li_len = as_data.length();
/*The length of the string buffer is longer than the original string*/
StringBuffer lsb_encode = new StringBuffer(li_len + (li_len/10));
/* Loop to replace all < and > characters*/
for(int li_count = 0; li_count < li_len; li_count++)
{ String ls_next = String.valueOf(as_data.charAt(li_count));
if (ls_next.equals("<")) ls_next = "<";
if (ls_next.equals(">")) ls_next = ">";
lsb_encode.append(ls_next);
}
return(lsb_encode.toString());
}
}
⑶ Create a tag processor. The tag processor uses the following code:
HTML encoding tag processor
import Java.io.IOException;
import Javax.servlet.jsp.*;
import Javax.servlet.jsp.tagext.*;
public class HTML_FormatTag extends BodyTagSupport
{
/* 1} This function will be called at the end of the tag*/
public int doEndTag() throws JspTagException
{
try
{ /* 2} Get the text in the label */
BodyContent l_tagbody = getBodyContent();
String ls_output = "";
/* 3} If the tag body has text, process it */
if(l_tagbody != null)
{ HTML_Format l_format = new HTML_Format();
/* 3a} Convert the content of the tag body into a string */
String ls_html_text = l_tagbody.getString();
ls_output = l_format.HTML_Encode(ls_html_text);
}
/* 4}Write the results back to the data stream*/
pageContext.getOut().write(ls_output.trim());
}
catch (IOException e)
{ throw new JspTagException("Tag Error:" + e.toString());
}
/* Let JSP continue to process the content of the following pages*/
return EVAL_PAGE;
}
}
This processing is very simple, it includes:
o Read the text between the beginning and end of the tag o Call the html encoding function o Return the result to the JSP page.
⑷ Creating a tag descriptor needs to describe the custom tag so that the system knows how to process it. The suffix of this description file is .tld, usually its name is the same as the tag processor, and it is stored in the "/WEB-INF/" directory.
HTML encoding tag descriptor
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
" http://Java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd ">
<TAGLIB>
<TLIBVERSION>1.0</TLIBVERSION>
<JSPVERSION>1.1</JSPVERSION>
<SHORTNAME>HTML_FormatTag</SHORTNAME>
<URI></URI>
<INFO>HTML Encoding Tag </INFO>
<TAG>
<NAME>HTMLEncode</NAME>
<TAGCLASS>HTML_FormatTag</TAGCLASS>
<INFO>Encode HTML</INFO>
</TAG>
</TAGLIB>
⑸ Update the Web XML file to now tell the JSP container to use the tag library. To do this, you need to modify the web.xml file. Specifically, you need to add a taglib project to register the tag library. Most importantly, assign a URI to the tag. A URI is a unique reference that applies only to this particular tag on the website. It is a good practice to use the full URL or package name to ensure uniqueness since the tag can be used on different websites. This example is simplified.
Modify web.xml file
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
" http://Java.sun.com/j2ee/dtds/web-app_2.2.dtd ">
<WEB-APP>
<TAGLIB>
<TAGLIB-URI>
HTMLEncode
</TAGLIB-URI>
<TAGLIB-LOCATION>
/WEB-INF/HTML_FormatTag.tld
</TAGLIB-LOCATION>
</TAGLIB>
</WEB-APP>
⑹ The custom tag using new tags has been set up and can be used on a JSP page. To do this, simply declare the tag on the page using the taglib directive. The tag is referenced by its unique URI and is assigned a namespace prefix. The prefix can be arbitrary as long as it does not conflict with other namespaces.
Use HTML encoding tags on a JSP page:
<%@ taglib uri="HTMLEncode" prefix="Examples" %>
<PRE>
<?XML:NAMESPACE PREFIX = Examples /><Examples:HTMLEncode>
<Hello, Simple sample>
</Examples:HTMLEncode>
</PRE>
Sample code output
<Hello, Simple sample>
which displays as:
<Hello, Simple sample>
With this tag, I encoded all the code of the page. The interesting thing is that all custom tags are handled on the server. This means you won't see custom tags on the output page.
It is not difficult to create a label. The hardest part is learning all the ins and outs of label processing. This is a very powerful feature, and we've only touched on the basics. Because this process requires several steps, new JSP programmers will be confused when creating tags.
How to use JSP to develop DOM applications?
DOM is the abbreviation of Document Object Model, which is the document object model. XML organizes data into a tree, so DOM is an object description of this tree. In layman's terms, it is to logically build a tree model for the XML document by parsing the XML document, and the nodes of the tree are objects. We can access the content of XML documents by accessing these objects.
Let's look at a simple example below to see how we operate an XML document in the DOM. This is an XML document and the object we want to operate on:
<?xml version="1.0" encoding="UTF-8"?>
<messages>
<message>Good-bye serialization, hello Java!</message>
</messages>
Next, we need to parse the content of this document into Java objects for use by the program. Using JAXP, we can do this with just a few lines of code. First, we need to create a parser factory to use this factory to obtain a specific parser object:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
The purpose of using DocumentBuilderFacotry here is to create a program that is independent of the specific parser. When the static method newInstance() of the DocumentBuilderFactory class is called, it determines which parser to use based on a system variable. And because all parsers obey the interface defined by JAXP, the code is the same no matter which parser is used. So when switching between different parsers, you only need to change the values of system variables without changing any code. This is the benefit of the factory.
DocumentBuilder db = dbf.newDocumentBuilder();
After obtaining a factory object, use its static method newDocumentBuilder() method to obtain a DocumentBuilder object, which represents a specific DOM parser. But which parser it is, Microsoft's or IBM's, is not important to the program.
Then, we can use this parser to parse the XML document:
Document doc = db.parse("c:/xml/message.xml");
The parse() method of DocumentBuilder accepts an XML document name as an input parameter and returns a Document object. This Document object represents a tree model of an XML document. All future operations on XML documents have nothing to do with the parser and can be operated directly on this Document object. The specific method of operating Document is defined by the DOM.
Starting from the obtained Document object, we can start our DOM journey. Using the getElementsByTagName() method of the Document object, we can get a NodeList object. A Node object represents a tag element in an XML document, and the NodeList object, as you can see from its name, represents a Node object. List:
NodeList nl = doc.getElementsByTagName("message");
What we get through such a statement is a list of Node objects corresponding to all <message> tags in the XML document. Then, we can use the item() method of the NodeList object to get each Node object in the list:
Node my_node = nl.item(0);
When a Node object is created, the data stored in the XML document is extracted and encapsulated in the Node. In this example, to extract the content within the Message tag, we usually use the getNodeValue() method of the Node object:
String message = my_node.getFirstChild().getNodeValue();
Please note that a getFirstChild() method is also used here to obtain the first child Node object under the message. Although there are no other sub-tags or attributes under the message tag except text, we insist on using the getFirseChild() method here, which is mainly related to the W3C's definition of DOM. W3C also defines the text part within the tag as a Node, so we must first get the Node representing the text before we can use getNodeValue() to obtain the content of the text. Now, since we have been able to extract the data from the XML file, we can use this data in the appropriate place to build the application.
DOM Example
Let's first talk about what this example is going to do. We have saved some URL addresses in a file named link. The added URL address is written in this XML file. It is very simple, but very practical, and it is enough to illustrate most of the usage of DOM.
The first program is called xmldisplay.Java. Its main function is to read the contents of each node in this XML file, and then format the output on System.out. Let’s take a look at this program:
import Javax.xml.parsers .*;
import org.w3c.dom.*;
This is to introduce the necessary classes, because the XML parser provided by Sun is used here, so the Java.xml.parsers package needs to be introduced, which contains the DOM parser and SAX parsing. The specific implementation of the device. The org.w3c.dom package defines the DOM interface developed by w3c.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("links.xml");
doc.normalize();
In addition to the above, there is also a little trick. Calling normalize() on the Document object can remove unnecessary Text Node objects mapped in the DOM tree as blanks in the XML document as formatted content. . Otherwise the DOM tree you get may not be what you imagined. Especially when outputting, this normalize() is more useful.
NodeList links =doc.getElementsByTagName("link");
As mentioned just now, whitespace characters in XML documents will also be mapped as objects in the DOM tree. Therefore, directly calling the getChildNodes method of the Node method sometimes has some problems, and sometimes it cannot return the expected NodeList object. The solution is to use Element's getElementByTagName(String), and the NodeLise returned is the expected object. Then, you can use the item() method to extract the desired element.
for (int i=0;i<links.getLength();i++){
Element link=(Element) links.item(i);
System.out.print("Content: ");
System.out.println(link.getElementsByTagName("text").item(0).getFirstChild();
.getNodeValue());
...
The above code snippet completes the formatted output of the XML document content. As long as you pay attention to some details, such as the use of getFirstChile() method and getElementsByTagName() method, these are relatively easy.
The following content is about rewriting the DOM tree into the XML document after modifying it. This program is called xmlwrite.Java. In the JAXP 1.0 version, there are no direct classes and methods that can handle the writing of XML documents, and you need to use some auxiliary classes in other packages. In the JAXP 1.1 version, support for XSLT was introduced. The so-called XSLT is to obtain a new document structure after transforming the XML document (Translation). Using this newly added function, we can easily write the newly generated or modified DOM tree back to the XML file. Let's take a look at the implementation of the code. The main function of this code is to link Add a new link node to the .xml file:
import Javax.xml.parsers.*;
import Javax.xml.transform.*;
import Javax.xml.transform.dom.DOMSource;
import Javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;
Several classes in the newly introduced Java.xml.transform package are used to handle XSLT transformations.
We hope to add a new link node to the above XML file, so we must first read the links.xml file, build a DOM tree, then modify the DOM tree (add nodes), and finally add the modified DOM Write back to the links.xml file:
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder=factory.newDocumentBuilder();
Document doc=builder.parse("links.xml");
doc.normalize();
//---Get variables----
String text="Hanzhong's Homepage";
String url=" www.hzliu.com ";
String author="Hzliu Liu";
String description="A site from Hanzhong Liu, give u lots of suprise!!!";
In order to see the key points clearly and simplify the procedure, we hard-code the content to be added into the memory String object. In actual operation, we often use a interface to extract user input, or extract the desired content from the database via JDBC.
Text textseg;
Element link=doc.createElement("link");
First of all, it should be clear that no matter what type of Node, whether it is Text type, Attr type, or Element type, they are all created through Document object CreateXXX() method in (XXX represents the specific type to be created), therefore, we need to add a link item to the XML document, first create a link object:
Element linktext=doc.createElement("text") ;
textseg=doc.createTextNode(text);
linktext.appendChild(textseg);
link.appendChild(linktext);
...
The process of creating nodes may be a bit uniform, but what needs to be noted is that the text contained in Element (in the DOM, these texts also represent a Node, so corresponding nodes must also be created for them). Directly use the setNodeValue() method of the Element object to set the content of these texts, and you need to use the setNodeValue() method of the created Text object to set the text, so that the created Element and its text content can be added to the DOM tree. Take a look at the previous code and you'll understand this better:
doc.getDocumentElement().appendChild(link);
Finally, don't forget to add the created node to the DOM tree. The getDocumentElement() method of the Document class returns the Element object representing the root node of the document. In an XML document, the root node must be unique.
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new Java.io.File("links.xml"));
transformer.transform(source, result);
Then use XSLT to output the DOM tree. The TransformerFactory here also applies the factory pattern, making the specific code independent of the specific transformer. The implementation method is the same as DocumentBuilderFactory, so I won’t go into details here. The transfrom method of the Transformer class accepts two parameters, a data source Source and an output target Result. DOMSource and StreamResult are used here respectively, so that the contents of the DOM can be output to an output stream. When the output stream is a file, the contents of the DOM are written to the file.
How to use JSP to develop SAX applications?
SAX is the abbreviation of Simple API for XML. It is not an official standard proposed by W3C. It can be said to be a "folk" de facto standard. In fact, it is the product of a community discussion. Even so, SAX is no less used in XML than DOM, and almost all XML parsers support it.
Compared with DOM, SAX is a lightweight method. We know that when processing DOM, we need to read the entire XML document, then create a DOM tree in memory and generate each Node object on the DOM tree. When the document is small, this does not cause any problems, but once the document becomes larger, processing the DOM becomes quite time-consuming and laborious. In particular, its memory requirements will also increase exponentially, so that using DOM in some applications is not cost-effective (such as in applets). At this time, a better alternative solution is SAX.
SAX is conceptually completely different from DOM. First of all, unlike the DOM document driver, it is event-driven, that is to say, it does not need to read the entire document, and the document reading process is also the SAX parsing process. The so-called event-driven refers to a program running method based on the callback mechanism. (If you are clear about Java's new proxy event model, you will easily understand this mechanism.) The XMLReader accepts the XML document and parses it during the process of reading the XML document, that is to say, the process of reading the document. The parsing process is carried out at the same time, which is very different from DOM. Before parsing starts, you need to register a ContentHandler with XMLReader, which is equivalent to an event listener. Many methods are defined in ContentHandler, such as startDocument(), which customizes what should be handled when the document starts to be encountered during the parsing process. matter. When XMLReader reads the appropriate content, it will throw the corresponding event, delegate the processing power of this event to ContentHandler, and call its corresponding method to respond.
It may be a bit difficult to understand in a general way, but don't worry, the following examples will help you understand the SAX parsing process. Take a look at this simple XML file:
<POEM>
<AUTHOR>Ogden Nash</AUTHOR>
<TITLE>Fleas</TITLE>
<LINE>Adam</LINE>
</POEM>
When XMLReader reads the <POEM> tag, it calls the ContentHandler.startElement() method and passes the tag name POEM as a parameter. Corresponding actions need to be taken in the startElement() method you implement to handle what should be done when <POEM> appears. Each event is thrown out one by one along with the parsing process (that is, the process of document reading), and the corresponding methods are also called sequentially. Finally, when the parsing is completed and the methods are called, the document is processed. That's it. The following table lists the methods that are called sequentially when parsing the XML file above:
Encountered project method callback
{document start} startDocument()
<POEM> startElement(null,"POEM",null,{Attributes})
"n" characters("<POEM>n...", 6, 1)
<AUTHOR> startElement(null,"AUTHOR",null,{Attributes})
"Ogden Nash" characters("<POEM>n...", 15, 10)
</AUTHOR> endElement(null,"AUTHOR",null)
"n" characters("<POEM>n...", 34, 1)
<TITLE> startElement(null,"TITLE",null,{Attributes})
"Fleas" characters("<POEM>n...", 42, 5)
</TITLE> endElement(null,"TITLE",null)
"n" characters("<POEM>n...", 55, 1)
<LINE> startElement(null,"LINE",null,{Attributes})
"Adam" characters("<POEM>n...", 62, 4)
</LINE> endElement(null,"LINE",null)
"n" characters("<POEM>n...", 67, 1)
</POEM> endElement(null,"POEM",null)
{End of document} endDocument()
ContentHandler is actually an interface. When processing a specific XML file, you need to create a class that implements ContentHandler to handle specific events. It can be said that this is actually SAX processing XML. The core of the document. Let's take a look at some of the methods defined in it:
void characters(char[] ch, int start, int length): This method is used to process the string read in the XML file. Its parameter is a character array and the starting point of the read string in this array. Starting position and length, we can easily use a constructor of the String class to obtain the String class of this string: String charEncontered=new String(ch,start,length).
void startDocument(): When you encounter the beginning of the document, call this method to do some preprocessing work.
void endDocument(): Corresponding to the above method, when the document ends, this method is called to do some aftermath work.
void startElement(String namespaceURI, String localName, String qName, Attributes atts): This method will be triggered when a start tag is read. Namespaces are not supported in the SAX1.0 version, but support for namespaces is provided in the new 2.0 version. The namespaceURI in the parameter here is the namespace, localName is the label name, and qName is the modified prefix of the label. If there is no When using namespaces, neither parameter is null. And atts is the list of attributes contained in this tag. Through atts, you can get all attribute names and corresponding values. It should be noted that an important feature of SAX is its streaming processing. When encountering a tag, it will not record the tags encountered before. In other words, in the startElement() method, all The information you know is the name and attributes of the tag. As for the nested structure of the tag, the name of the upper tag, whether there are sub-element attributes, and other structure-related information, it is unknown and needs your help. program to complete. This makes SAX less convenient for programming than DOM.
void endElement(String namespaceURI, String localName, String qName): This method corresponds to the above method. This method is called when an end tag is encountered.
We still use the document example we used when talking about DOM, but first, let's look at a simpler application. We hope to count the number of times each tag appears in an XML file. This example is very simple, but it is enough to illustrate the basic ideas of SAX programming. Of course, the import statement is still used at the beginning:
import org.xml.sax.helpers.DefaultHandler;
import Javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import Java.util.*;
import Java.io.*;
Then, we create a class that inherits from DefaultHandler. The specific program logic can be put aside for the time being. What we should pay attention to is the structure of the program:
public class SAXCounter extends DefaultHandler {
private Hashtable tags; //This Hashtable is used to record the number of times the tag appears
//Work before processing the document
public void startDocument() throws SAXException {
tags = new Hashtable();//Initialize Hashtable
}
//Process each starting element attribute
public void startElement(String namespaceURI, String localName,
String rawName, Attributes atts)
throws SAXException
{
String key = localName;
...
Let's see what this program does. In the main() method, the main thing you do is to create a parser and then parse the document. In fact, when creating the SAXParser object here, in order to make the program code independent of the specific parser, the same design technique as in the DOM is used: create a specific SAXParser object through a SAXParserFactory class, so that when different When parsing, all that needs to be changed is the value of an environment variable, while the program code can remain unchanged. This is the idea of FactoryMethod pattern. I won’t go into details here. If you still don’t understand, you can refer to the explanation in the DOM above. The principle is the same.
But there is one thing to note here, which is the relationship between the SAXParser class and the XMLReader class. You may be a little confused. In fact, SAXParser is a wrapper class for XMLReader in JAXP, and XMLReader is an interface defined in SAX2.0 for parsing documents. You can also call the parser() method in SAXParser or XMLReader to parse the document, and the effect is exactly the same. However, the parser() method in SAXParser accepts more parameters and can parse different XML document data sources, so it is more convenient to use than XMLReader.
This example only touches the surface of SAX, but the following one is more advanced. The function we want to implement below has already been implemented in the DOM example, which is to read the content from the XML document and format the output. Although the program logic still looks very simple, SAX is no better than DOM. Just watch.
As mentioned before, when encountering a start tag, in the startElement() method, we cannot get the position of the tag in the XML document. This is a big trouble when processing XML documents, because the semantics of tags in XML are partly determined by their location. And in some programs that need to verify the structure of the document, this is even more of a problem. Of course, there is no problem that cannot be solved. We can use a stack to record the document structure.
The characteristic of the stack is first in, first out. Our current idea is to use push to add the name of the label to the stack in the startElemnt() method, and pop it out in the endElement() method. We know that for a well-structured XML, its nesting structure is complete. Each start tag always corresponds to an end tag, and there will be no misalignment between tag nesting. Therefore, every call to the startElement() method will inevitably correspond to a call to the endElement() method, so push and pop also appear in pairs. We only need to analyze the structure of the stack to easily know where the current label is. position in the document structure.
public class SAXReader extends DefaultHandler {
Java.util.Stack tags=new Java.util.Stack();
...
Although stack analysis is not used here, stack analysis is actually a very easy task. It should be because Java.util.Stack inherits the Java.util.Vector class, and the elements in Stack are stack-based. The structure is arranged from bottom to top. Therefore, we can use the size() method of the Vector class to get the number of elements in the Stack, and we can also use the get(int) method of the Vector class to get the specific attributes of each element. In fact, if we arrange the elements of the Stack one by one from bottom to top, we will get a unique path from the XML root node to the current node. With the information of this path, the structure of the document will be clear.
So far, we have mastered the two major tools for XML programming: DOM and SAX, and also know how to use them in a Java program. DOM programming is relatively simple, but slow and takes up a lot of memory, while S AX programming is more complex, but fast and takes up less memory. Therefore, we should choose to use different methods according to different environments. Most XML applications can basically be solved using them. It should be noted that DOM and SAX are actually language-independent and are not unique to Java. In other words, as long as there is a corresponding language implementation, DOM and SAX can be applied in any object-oriented language.