Java Xml 简明教程
Java StAX Parser - Overview
StAX 是一个基于 Java 的 API,用于以与 SAX 解析器相同的方式解析 XML 文档。但与 SAX 解析器不同,StAX 解析器 API 是一个简单的基于迭代器的 API,它将解析控制权授予客户端程序。它以仅限前向的方式读取 XML 文档并将事件存储在迭代器中。
StAX is a Java-based API to parse XML document in a similar way as SAX parser does. But unlike SAX parser, the StAX parser API is a simple iterator based API that gives parsing control to the client program. It reads the XML document in a forward-only fashion and stores the events in an iterator.
客户端可以根据每个事件的事件类型询问想要访问的事件。
The client can ask for the events that he wants to access based on the event type of each event.
Differences Between SAX and StAX Parsers
以下是 SAX 和 StAX 解析器之间的一些显著差异:
Here are some notable differences between SAX and StAX parsers −
Environment Setup
为了使用 StAX 解析器,您应该在应用程序的类路径中包含 stax.jar 。
In order to use StAX parser, you should have stax.jar in your application’s classpath.
Features of StAX
以下是 StAX API 的特性:
Following are the features of StAX API −
-
Reads the XML document from top to bottom and identifies the tokens.
-
Processes the tokens in the same order of their appearance.
-
Reports the parser about the nature of the tokens.
-
Invokes the callback methods in the Event handler based on the identified tokens.
When to Use Java StAX Parser?
您应该在以下情况下使用 StAX 解析器:
You should use a StAX parser when −
-
You want to process an XML document in a linear fashion from top to bottom.
-
The document is not deeply nested.
-
Your XML document is very large.
-
The problem to be solved involves only a part of the XML document.
-
You have streaming data (data is available as soon as it is seen by the parser).
Disadvantages of StAX
以下是 SAX 解析器的缺点:
Following are the disadvantages of StAX parser −
-
We have no random access to an XML document, since it is processed in a forward-only manner.
-
XML schema validation is not supported.
-
If you need to keep track of data that the parser has seen or where the parser has changed the order of items, then you must write the code and store the data on your own.
XMLEvent Interface
此界面提供 XML 文档所有组件的基本事件表示形式。事件类型区分各个事件,并相应地检索信息。此界面的某些最常用的方法如下−
This interface provides the basic Event representation of all components of an XML document. The event type differentiates each event and the information is retrieved accordingly. Some of the most commonly used methods of this interface are as follows −
XMLEventReader Interface
此界面提供事件迭代器,可用于遍历在解析 XML 文档时发生的事件。某些最常用的方法如下所示−
This interface provides iterator of events which can be used to iterate over events as they occur while parsing an XML document. Some of the most commonly used methods are listed below −
XMLEventWriter Interface
此界面通过添加事件来写入 XML 文档。某些最常用的方法如下所示−
This interface writes XML documents by adding events. Some of the most commonly used methods are listed below −