The combination of JSP and XML

Source: Internet
Author: User
Tags array definition event listener implement interface object model tostring stringbuffer
Js|xml Overview: Extensible Markup Language (extensible Markup language,xml) is being quickly applied to the industry, and it has been used as a widely used standard for describing and exchanging data in formats that are not platform, language, and protocol-independent. XML and its auxiliary specification can be used to describe the document performance of the data, describe the constraints of XML document types, describe the links between XML documents and resources, and describe the automatic conversion and formatting of XML documents.

How do I develop a custom tag library?

I have been using JSP and ASP programming for quite a long time, in two kinds of server-side programming, I increasingly feel that JSP functions more powerful. Without mentioning anything else, the JSP's tag library is why I chose JSP as the preferred server-side Web application development tool. Why? Because: the speed of maintenance and development. In a single server page, you can mix the various scripting methods and objects. Just like quot concrete, this mix makes server-side scripts powerful and allows server-side programmers to design very flexible and dynamic web pages. But this kind of free mix also has its disadvantage, that is maintenance is very troublesome, especially when the project is getting bigger. Because the final product is maintained by a traditional web designer, it can cause problems. Worse, as the complexity of the code increases, the speed of development slows down and is not conducive to the development of medium and large Web applications, and once developed, the site also has to find qualified programmers to maintain these rather complex code.
Fortunately, JSP provides a good solution. The tag library provides a simple way to build a reusable block of code. Once the tag library is well designed, it can be reused in many projects. More conveniently, unlike COM and Java EE, you can build a tag library without learning any other tricks! As long as you know how to write JSP, you can build a tag library. Tag libraries can also improve the maintenance of Web applications. This is a simple XML interface that benefits from JSP page custom tags. In this way, web designers can even build JSP Web applications without having to know any JSP knowledge. This open web development is very effective for team operations. JSP programmers can create custom tags and backend code modules, and web designers can use custom tags to build Web applications and focus on web design.

1. Definition of Tag Library
JSP tag libraries (also called custom libraries) can be viewed as a set of methods that generate xml-based scripts that are supported by JavaBeans. Conceptually, a tag library is a very simple and reusable code construct.
Perform xml/xsl conversion of tag examples and HTML pages

<%@ taglib uri= "Http://www.jspinsider.com/jspkit/JAXP" prefix= "JAXP"%>
C:/xml/example.xml
C:/xml/example.xsl

In this example, by using a simple tag to access the more powerful code in the background, an XML is loaded, and an XSL file is used to produce a result that is sent to the client, all by using a simple tag call.
Custom tags open a door to creating easily reusable code in a JSP project. All you need is a tag library and a description of its documentation.

2. Component of the label
Although the tag library is very easy to use, it is quite complicated to build a design inside to support the tag library, at least more complex than building a simple javabean. This complexity comes from the tag library that is made up of several parts. However, you only need to know the Java and JSP knowledge is enough.
A simple label is composed of the following elements:
⑴javabeans: To get Java and raw object-oriented benefits, reusable code should be placed in a separate code container. These JavaBeans are not part of the tag library. But it's the basic block of code your code base uses to perform related tasks.
⑵ Label Processing: This is the true core of the tag library. A label processor will refer to whatever resources it needs (your JavaBeans) and access to all the information (PageContext objects) of your JSP page. The JSP page also transmits all the label properties that have been set and the contents of the label body on the JSP page to the label processor. After the label processor has finished processing, it will be sent back to your JSP page for processing.
Description of the ⑶ tag library (TLD file): This is a simple XML file that records the properties, information, and location of the label processor. The JSP container uses this file to learn where and how to invoke a tag library.
Web.xml file for ⑷ website: This is the initialization file for your site, in which you define the custom tags used in the site and which TLD file describes each custom label.
⑸ distribution file (a war or jar file): If you want to reuse a custom label, you need a way to transfer it from one project to another. Packaging a tag library as a jar file is a simple and effective way to do this.
⑹ in your JSP file as a tag library statement: Very simple, if you want to use the tag, as long as the page declaration can be, then, you can use it anywhere on the JSP page.
There seems to be a lot of work to do, but it's not very difficult. Its main point is not coding, but how to organize the parts correctly. However, such layering is important to make the labels flexible and easier to move. More importantly, the presence of these layers enables the processing of tagging projects to be done automatically through a JSP IDE (integrated development environment for JSP). Expect the future JSP IDE to automate most of the work of creating a custom label, so you just need to write code and tag processing.
Note: A label processing defines only a custom label; a tag library is a collection of several label processors that handle the same tasks.

3. Create your own label
Here's how to create a custom label step-by-step, with an example of extending the 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 coding processing. To simplify, this example only explains the basics of creating a custom label.
⑴ Create a JavaBean
Any reusable part of your code should be placed in a javabean. This is important because you often use the code elsewhere in the project. Any code placed in the label processor cannot be reused outside of the label, so it is important to separate the reusable code parts. In this example, the logic for HTML encoding is often used, so put it in the JavaBean.
⑵html Coding JavaBean

* Html_format.java * *
public class Html_format extends Object implements Java.io.Serializable {
/** Create a new Html_format * *
Public Html_format () {}
/** replaces the HTML encoding of all < and > characters in a string with the used response.
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 replaces 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 label processor
The label processor uses the following code:

HTML Coded label processor
Import Java.io.IOException;
Import javax.servlet.jsp.*;
Import javax.servlet.jsp.tagext.*;
public class Html_formattag extends Bodytagsupport
{
/* 1} will call this function at the very weekend of the label * *
public int Doendtag () throws Jsptagexception
{
Try
{/* 2} Gets the text in the label * *
Bodycontent l_tagbody = Getbodycontent ();
String ls_output = "";
/* 3} If the label body has text, deal with it * *
if (l_tagbody!= null)
{Html_format L_format = new Html_format ();
/* 3a} Converts the contents of the label body to a string * *
String Ls_html_text = l_tagbody.getstring ();
Ls_output = L_format. Html_encode (Ls_html_text);
}
/* 4} Writes the result 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 contents of the following pages.
return eval_page;
}
}

This process is simple, and it includes:
o Read the text between the beginning and the end of the label
o Call HTML encoding function
o return results to JSP page.
⑷ Create a tag descriptor
You need to describe a custom label to let the system know how to handle it. The suffix of the description file is. TLD, which is usually the same name as the label processor, and is stored in the "/web-inf/" directory.

HTML Coded 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 Web XML file
You can now tell the JSP container to use the tag library. To do this, modify the Web.xml file, specifically by adding a taglib project to register the tag library. The most important thing is to assign a URI to the tag. A URI is a unique reference that applies only to this particular label on the site. Using a full length URL or package name is a good habit to ensure uniqueness because the tag can be used on different sites. This example is simplified.

modifying Web.xml files
<?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>

⑹ Use the new label
The custom label has been set up and can be used on a JSP page. To do this, simply use the taglib Instruction command on the page to declare the label, which is referenced through its unique URI, and is assigned a namespace prefix. The prefix can be arbitrary, as long as it does not conflict with the other name space.
To 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>
Output of the sample code
< Hello, simple sample >
which displays as:
< Hello, simple sample >

With this tag, I coded all the code for the page. Interestingly, all custom tags are processed on the server. This means that you will not see the custom label on the output page.
It's not hard to build a label. The hardest part is to learn all the details of the label processing. This is a very powerful function, we just mentioned the most basic place. As this process takes a few steps, the new JSP programmer will be puzzled when creating the label.

How do I use JSP to develop DOM applications?

The DOM is the acronym for Document Object Model, which is the documentation objects module. XML organizes data into a tree, so DOM is a description of an object to the tree. In layman's parlance, it is to create a tree model logically for XML documents by parsing XML documents, and the nodes of the tree are objects. By accessing these objects, we are able to access the contents of the XML document.
Let's look at a simple example of how we can manipulate an XML document in the DOM. This is an XML document and is the object we want to manipulate:

<?xml version= "1.0" encoding= "UTF-8"?>
<messages>
<message>good-bye serialization, Hello java!</message>
</messages>

Next, we need to parse the contents of this document into a single Java object for the program to use, and with JAXP we can do this with just a few lines of code. First, we need to build a parser factory to use this factory to get a specific parser object:
Documentbuilderfactory dbf = Documentbuilderfactory.newinstance ();
The purpose of using documentbuilderfacotry here is to create a program that is not specific to a parser, when the static method of the Documentbuilderfactory class newinstance () is invoked, It determines which parser to use depending on a system variable. And because all parsers are subject to the interfaces defined by JAXP, the code is the same regardless of which parser is used. So when you switch between different parsers, you just need to change the value of the system variable without changing any of the code. This is the benefit that the factory brings.
Documentbuilder db = Dbf.newdocumentbuilder ();
When a factory object is obtained, the static method Newdocumentbuilder () method is used to obtain a Documentbuilder object that represents the specific DOM parser. But what kind of parser, Microsoft or IBM, is not important for the program.
We can then use this parser to parse the XML document:
Document doc = Db.parse ("C:/xml/message.xml");
Documentbuilder's Parse () method takes an XML document name as an input parameter and returns a Document object that represents the tree model of an XML document. All future operations on XML documents have nothing to do with the parser, and you can do it directly on the document object. The specific approach to document manipulation is defined by the DOM.
Starting with the resulting Document object, we can start our DOM trip. Using the getElementsByTagName () method of the Document object, we get a NodeList object, a Node object that represents a LABEL element in an XML document, and the NodeList object, known by its name, Represents a list of node objects:
NodeList nl = doc.getelementsbytagname ("message");
What we get through such a statement is the node object of all the <message> tags in the XML document.
A list. We can then 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 contents of the message label, we typically use the Getnodevalue () method of the Node object:
String message = My_node.getfirstchild (). Getnodevalue ();
Note that a getfirstchild () method is also used here to get the first child node object under the message. Although there are no other child tags or attributes underneath the message label, we insist on using the Getfirsechild () method here, which is primarily related to the definition of DOM by the consortium. The consortium defines the text part of the label as a node, so we get to the node that represents the text before we can use Getnodevalue () to get the content of the text. Now that we've been able to extract the data from the XML file, we can use the data in the right place to build the application.

Dom Instance

Let's start with what this example is all about, we've saved some URL addresses in a file named Link.xml, we want to be able to read and display these URLs through the DOM, and we can also write the added URL address to the XML file. It's simple, but it's practical, and it's enough to sample the most usage of DOM.
The first program we call Xmldisplay. Java, the main function is to read the contents of the nodes in this XML file, and then in the format of the output on the System.out, we look at this program:

Import javax.xml.parsers.*;
Import org.w3c.dom.*;

This is the introduction of the necessary class, because it uses the XML parser provided by Sun, which requires the introduction of the Java.xml.parsers package, which contains the concrete implementations of the DOM parser and the SAX parser. The Org.w3c.dom package defines the DOM interface established by the consortium.

Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Documentbuilder Builder=factory.newdocumentbuilder ();
Document doc=builder.parse ("Links.xml");
Doc.normalize ();

In addition to the above, there is a small trick to call normalize () on the Document object, which removes the unnecessary text node objects in the XML document that are mapped in the DOM tree as whitespace from the formatted content. Otherwise you may get a DOM tree that is not what you think it is. Especially in the output, this normalize () is more useful.

NodeList links =doc.getelementsbytagname ("link");

Just now, whitespace in an XML document is also mapped as an object in the DOM tree. Thus, the Getchildnodes method that calls the node method directly sometimes has problems and sometimes does not return the desired NodeList object. The solution is to use element Getelementbytagname (String), and the returned nodelise is the object of expectation. You can then 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 code snippet above completes the formatted output of the XML document content. As long as you notice the details of the problem, such as the Getfirstchile () method and the use of the getElementsByTagName () method, these are relatively easy.
The following is the question of writing back to the XML document after modifying the DOM tree. This program is named Xmlwrite. Java. In the JAXP1.0 version, there are no direct classes and methods that can handle writing problems with XML documents, and need to use some of the auxiliary classes in other packages. In the JAXP1.1 version, the introduction of the support for XSLT, the so-called XSLT, is the transformation of XML documents (translation), a new document structure. With this new addition, we can easily write the newly generated or modified DOM tree back to the XML file, let's look at the implementation of the Code, the main function of which is to add a new link node to the Links.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 want to add a new link node to the XML file above, so we'll start by reading the Links.xml file, building a DOM tree, then modifying the DOM tree (adding nodes), and finally writing the modified Dom back into the Links.xml file:

Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Documentbuilder Builder=factory.newdocumentbuilder ();
Document doc=builder.parse ("Links.xml");
Doc.normalize ();
---get the variable----
String text= "Hanzhong ' s homepage";
String url= "www.hzliu.com";
String author= "Hzliu Liu";
String discription= "A site from Hanzhong Liu, give u lots of suprise!!!";

To see the point and simplify the program, we hard-code the content to be added to the memory string object, and in practice, an interface is often used to extract user input, or to extract the desired content from the database through JDBC.

Text textseg;
Element link=doc.createelement ("link");

The first thing to understand is that no matter what type of node,text, attr or element, they are created by the Createxxx () method in the Document object (XXX represents the type to be created), so To add a link project to an XML document, we first create a link object:

Element linktext=doc.createelement ("text");
Textseg=doc.createtextnode (text);
Linktext.appendchild (TEXTSEG);
Link.appendchild (Linktext);
......

The process of creating a node may be a bit of a uniform one, but it should be noted that the text contained in the element (in the DOM, which also represents a node, and therefore must also create the appropriate node for them), You cannot set the contents of these text directly using the setNodeValue () method of the Element object, but you need to set the text with the setNodeValue () method of the text object you created so that you can add the created element and its text content to the DOM tree. Look at the previous code and you will better understand this:
Doc.getdocumentelement (). appendchild (link);
Finally, don't forget to add the created node to the DOM tree. The Getdocumentelement () method of the document class, which returns an Element object that represents the root node of documents. 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);

The DOM tree is then exported using XSLT. The Transformerfactory also applies the factory pattern, making the specific code irrelevant to the specific converter. The method of implementation is the same as documentbuilderfactory, here is not to repeat. The Transfrom method of the transformer class accepts two parameters, one data source and one output target result. The Domsource and Streamresult are used separately, so that the contents of the DOM can be exported to an output stream, and when the output stream is a file, the contents of the DOM are written to the file.

How do I use JSP to develop SAX applications?

Sax is the abbreviation of simple API for XML, it is not the standard that is put forward by the official of the consortium, it can be said as the "folk" fact standard. In fact, it is a community-nature discussion product. Even so, the application of Sax in XML is no less than DOM, and almost all XML parsers will support it.
Sax is a lightweight method compared to DOM. We know that when we work with DOM, we need to read the entire XML document and then create the DOM tree in memory to generate each node object on the DOM tree. This is not a problem when the document is small, but once the document is large, processing the DOM becomes quite time-consuming and laborious. In particular, the need for memory will be multiplied, so that using DOM in some applications is not a good deal (as in an applet). At this point, a better alternative solution is sax.
Sax is conceptually completely different from DOM. First, unlike the DOM document driver, it is event-driven, that is, it does not need to read the entire document, and the reading process of the document is the parsing process of sax. Event-driven refers to a program running method based on callback (callback) mechanism. (If you're more aware of the Java new Proxy event model, it's easy to understand this mechanism. XmlReader accepts XML documents and parses them as they are read into XML documents, which means that the process of reading the document and the parsing process are simultaneous, which differs greatly from DOM. Before parsing begins, you need to register a contenthandler with XmlReader, which is equivalent to an event listener, and a number of methods are defined in ContentHandler, such as Startdocument (), which customize the process of parsing What you should handle when you start a document. When XmlReader reads the appropriate content, it throws the corresponding event, and the handler for the event is given to ContentHandler to invoke its corresponding method to respond.
This may not be easy to understand in general, don't worry, the following example will let you understand the parsing process of sax. 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 label name POEM as an argument. In the Startelement () method you implement you need to do the appropriate action to handle what you should do when <POEM> appears. Each event with the process of parsing (that is, the process of reading the document) is thrown in sequence, the corresponding method will be called in sequence, and finally, when the resolution is completed, the method is called, the document processing is completed. The following table lists the methods that are called sequentially when parsing the XML file above:

The Project method callback encountered

{Document Start} startdocument ()
<POEM> startelement (null, "POEM", null,{attributes})
"" Characters ("<POEM> ...", 6, 1)
<AUTHOR> startelement (null, "AUTHOR", null,{attributes})
"Ogden Nash" characters ("<POEM> ...", 15, 10)
</AUTHOR> endelement (null, "AUTHOR", NULL)
"" Characters ("<POEM> ...", 34, 1)
<TITLE> startelement (null, "TITLE", null,{attributes})
"Fleas" characters ("<POEM> ...", 42, 5)
</TITLE> endelement (null, "TITLE", NULL)
"" Characters ("<POEM> ...", 55, 1)
<LINE> startelement (NULL, "line", null,{attributes})
"Adam" characters ("<POEM> ...", 62, 4)
</LINE> endelement (NULL, "line", null)
"" Characters ("<POEM> ...", 67, 1)
</POEM> endelement (null, "POEM", NULL)
{Document END} enddocument ()

ContentHandler is actually an interface that, when dealing with a particular XML file, needs to create a class that implements ContentHandler to handle a particular event, which is actually the core of the Sax processing XML file. Let's take a look at some of the methods defined here:
void characters (char[] ch, int start, int length): This method is used to read a string in an XML file, its argument is an array of characters, and the starting position and length of the string that is read in this array, We can easily use a constructor of the string class to get the string class of this character: string Charencontered=new string (ch,start,length).
void Startdocument (): When you encounter the beginning of a document, call this method, you can do some preprocessing work.
void Enddocument (): Corresponds to the above method, and when the document is finished, call this approach to do some cleanup work.
void Startelement (String NamespaceURI, String LocalName, String qName, Attributes Atts): This method is triggered when a start tag is read. Name domains are not supported in the SAX1.0 version, and support for name domains is provided in the new version 2.0, where the NamespaceURI in the parameter is the name domain, the localname is the label name, and the QName is the decorated prefix of the label, neither of which is null when the name field is not used. And Atts is the list of attributes that this tag contains. By Atts, you get all the property names and the corresponding values. Note that one of the important features of Sax is its flow processing, when a tag is encountered, it does not record the previously encountered tag, that is, in the Startelement () method, all you know is the name and attributes of the tag, and the nested structure of the tag, The name of the top tag, whether there are any other structure-related information, etc., are unknown and require your program to complete. This makes it so easy for sax to have no DOM on the programming process.
void EndElement (String NamespaceURI, String localname, String qName): This method corresponds to the above square method, which is called when the end tag is encountered.
We still follow the example of the document used when we talk about DOM, but first, let's look at a simple application that we want to be able to count the number of occurrences of each label in the XML file. This example is simple enough to illustrate the basic idea of sax programming. In the beginning, of course, the import statement:

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, where the specific program logic can be put aside for a while, and note the structure of the program:

public class Saxcounter extends DefaultHandler {
private Hashtable tags; This hashtable is used to record the number of times tag appears
Work before working with a document
public void Startdocument () throws Saxexception {
tags = new Hashtable ();//Initialize Hashtable
}
Dealing with each of the starting meta genera
public void Startelement (string NamespaceURI, String localname,
String Rawname, Attributes atts)
Throws Saxexception
{
String key = LocalName;
......

Let's take a look at what this procedure has done. In the main () method, the main thing to do is to create a parser and then parse the document. In fact, when creating a SAXParser object here, in order to make the program code irrelevant to a specific parser, you use the same design techniques as in the DOM: Create concrete SAXParser objects with a saxparserfactory class, so that When you need to use a different parser, the change is only the value of an environment variable, and the code of the program can remain unchanged. This is the thought of FactoryMethod mode. No more specifics here, and if there's something you don't understand, see the explanation in the DOM above, the principle is the same.
But there's a little bit more to note here, the relationship between the SAXParser class and the XmlReader class. You may be a little confused, actually SAXParser is a encapsulated class of XmlReader in Jaxp, and XmlReader is an interface defined in SAX2.0 to parse a document. You can also call SAXParser or XmlReader in the parser () method to parse the document, 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 involves only a little bit of sax, and the bottom one is more advanced. The functionality that we're going to implement here is already implemented in the DOM example, which is to read the content from the XML document and format the output, although the program logic looks simple, but sax is no better than Dom Oh, look at it.
As I said earlier, when we encounter a start tag, in the Startelement () method, we don't get the position of the tag in the XML document. This is a big hassle when working with XML documents, because the semantics of tags in XML are partly determined by where they are located. And in some programs that need to validate the structure of the document, this is a more problematic issue. Of course, there is no solution to the problem, we can use a stack to achieve the document structure record.
The feature of the stack is FIFO, and our idea is to add the name of the tag to the stack in the Startelemnt () method and pop it out in the EndElement () method. We know that for a well-formed XML, the nesting structure is complete, each start tag always corresponds to an end tag, and there is no mismatch between the label nesting. Therefore, every time the Startelement () method of the call, will necessarily correspond to a endelement () method of the call, so that the push and pop also appear in pairs, we only need to analyze the structure of the stack, you can easily know the current label in the document structure position.

public class Saxreader extends DefaultHandler {
Java.util.Stack tags=new Java.util.Stack ();
......

Although there is no use of the analysis of the stack, but in fact the stack analysis is a very easy thing, The Java.util.Vector class should be inherited for Java.util.Stack, and the elements in stack are arranged from bottom to top by the stack structure, because we can use the size () method of the vector class to get the number of elements in the stack. You can also use the vector get (int) method to obtain each of the specific genera. In fact, if the stack elements are sorted from bottom to top, we get a unique path from the XML root node to the current node, and with this path, the structure of the document is clear.
So far, we've mastered two great tools for XML programming: DOM and sax, and we know how to use them in a Java program. DOM programming is relatively simple, but slower and consumes more memory, while S-ax programming is a bit more complex, but fast and consumes less memory. Therefore, we should choose to use different methods according to different environment. Most of the XML applications can be solved by using them basically. Specifically, Dom and sax are language-independent, not unique to Java, which means that Dom and sax can be applied in any object-oriented language, as long as there is a corresponding language implementation.



Related Article

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.