Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java and SAX 2.0 to parse XML documents

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly shows you "how to use Java combined with SAX 2.0 to parse XML documents", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let Xiaobian lead you to study and learn "how to use Java combined with SAX 2.0 to parse XML documents" this article.

/ *

Since XML really came into being (I think it was when Org.w3c released the XML standard), XML has developed rapidly.

Many manufacturers have launched their own XML parsers, such as apache's xalan,IBM, xerces,sun 's Jdom, etc., but these are all in the

Based on JAXP (Java api for XML processing), JAXP has been attached to subsequent j2sdk starting with jdk 1.4.0, which gives developers

It brings great convenience, which makes us no longer need to use third-party XML processors when dealing with general XML functional problems.

With the rapid development of XML, SAX has changed from 1.0 to 2.0 (still compatible with 1.0), and there have been some great changes in structure.

DOM (document object model) every time you read the XML node, you have to load it into memory, and when the document is very large, it appears to be very slow. SAX (simple API for XML) is an interface of a XML parser, which is lower than DOM. It is a XML processing method based on events and callback patterns, so DOM is incomparable in parsing speed (especially when the XML document to be parsed is very large). So what is the event response (event) in SAX? Personally, I think this is somewhat similar to the event meaning in swing,AWT, which refers to the processing done when certain behaviors are triggered, such as the click event of mouse. Here refers to encounter a specific XML node to do the processing, such as document start (startDocument), document end (endDocument), element start (startElement) and so on a lot of, we take a look at SAX's API method name to know which events, basically can see the meaning of the text. When you only want to analyze XML content (read-only) and require high performance and flexibility to locate error messages (SAX can locate the rows and rows of errors), it's best to use SAX. In general, SAX is used according to the following principles:

Set event handlers (SAX 1.0 is set by inheriting an instance of the HandlerBase class, while SAX 2.0 inherits DefaultHandler and uses XMLReader, which does not differ much in principle)

Load the content to be parsed

Add your own control logic to the event methods that need to be parsed (see SAX API documentation for details).

Repeat until the parsing is finished.

Here I wrote a XML file (file.xml) describing the movie poster information, and wrote a very simple XML content reader with SAX2.0 to parse it and exchange my experience with you. The program has been tested on my machine (OS: Win2k Advanced Server (English version))

Intel pentium cpu, 256m RAM)

, /

Import org.w3c.dom.*

Import org.xml.sax.*

Import org.xml.sax.helpers.*

Import javax.xml.parsers.*

Class MyXMLReader extends DefaultHandler

{

/ / Fields

Private int index

Private Locator locator

/ / Constructor

Public MyXMLReader () {

Super (); / / it must be done!

}

/ / nain method

Public static void main (String [] args) {

Try {

SAXParserFactory sf = SAXParserFactory.newInstance ()

SAXParser sp = sf.newSAXParser ()

MyXMLReader reader = new MyXMLReader ()

Sp.parse (new Inputsource ("film.xml"), reader)

}

Catch (Exception e) {

E.printStackTrace ()

}

}

/ / Response the startDocument event

Public void startDocument () {

System.out.println ("nasty * (: New Year's Day Movie poster:) * * n")

}

/ / Response the startElement event

Public void startElement (String uri, String localName, String qName, Attributes attrs) {

If (qName.equalsIgnoreCase ("film")) {

Index + +

Int attrCount = attrs.getLength ()

For (int I = 0; I < attrCount; I + +) {

String attrName = attrs.getQName (I)

If (attrName.equalsIgnoreCase ("name")) {

System.out.println ("t" + index + "field, title:")

}

If (attrName.equalsIgnoreCase ("price")) {

System.out.println ("t fare:" + attrs.getValue (I))

}

If (attrName.equalsIgnoreCase ("station")) {

System.out.println ("t venue:" + attrs.getValue (I))

}

If (attrName.equalsIgnoreCase ("time")) {

System.out.println ("t screening time:" + attrs.getValue (I))

}

If (attrName.equalsIgnoreCase ("describtion")) {

System.out.println ("t movie introduction:" + attrs.getValue (I))

}

System.out.println ()

}

}

/ / Response the endDocument event

Public void endDocument () {

System.out.println ("ttttttt- share" + index + "Movie to be shown")

}

/ / Response the endElement event

Public void endElement (String uri, String localName, String qName) {

/ / add your codes if neccessary...

}

/ / Print the fata error information

Public void fatalError (SAXParseException e) {

System.out.println ("nFatal error information-& gt")

System.out.println ("t" + e.getMessage ())

System.out.println ("tAt line" + locator.getLineNumber () +

", column" + locator.getColumnNumber ()

}

/ / Print the usual error information

Public void error (SAXParseException e) {

System.out.println ("nUsual error information-& gt")

System.out.println ("t" + e.getMessage ())

System.out.println ("tAt line" + locator.getLineNumber () +

", column" + locator.getColumnNumber ()

}

/ / Print the warning information

Public void warning (SAXParseException e) {

System.out.println ("nWarning information-& gt")

System.out.println ("t" + e.getMessage ())

System.out.println ("tAt line" + locator.getLineNumber () +

", column" + locator.getColumnNumber ()

}

/ / Store the error locator object

Public void setDocumentLocator (Locator lct) {

Locator = lct

}

} / / End class MyXMLReader

Attached: the complete content of film.xml:

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report