Mapping XML to Java, Part 1 - JavaWorld August 2000
Tutorial Details:
Mapping XML to Java, Part 1
Mapping XML to Java, Part 1
By: By Robert Hustead
Employ the SAX API to map XML documents to Java objects
ML is hot. Because XML is a form of self-describing data, it can be used to encode rich data models. It's easy to see XML's utility as a data exchange medium between very dissimilar systems. Data can be easily exposed or published as XML from all kinds of systems: legacy COBOL programs, databases, C++ programs, and so on.
Mapping XML to Java: Read the whole series!
Part 1 -- Employ the SAX API to map XML documents to Java objects
Part 2 -- Create a class library that uses the SAX API to map XML documents to Java objects
However, using XML to build systems poses two challenges. First, while generating XML is a straightforward procedure, the inverse operation, using XML data from within a program, is not. Second, current XML technologies are easy to misapply, which can leave a programmer with a slow, memory-hungry system. Indeed, heavy memory requirements and slow speeds can prove problematic for systems that use XML as their primary data exchange format.
Some standard tools currently available for working with XML are better than others. The SAX API in particular has some important runtime features for performance-sensitive code. In this article, we will develop some patterns for applying the SAX API. You will be able to create fast XML-to-Java mapping code with a minimum memory footprint, even for fairly complex XML structures (with the exception of recursive structures).
In Part 2 of this series, we will cover applying the SAX API to recursive XML structures in which some of the XML elements represent lists of lists. We will also develop a class library that manages the navigational aspects of the SAX API. This library simplifies writing XML mapping code based on SAX.
Mapping code is similar to compiling code
Writing programs that use XML data is like writing a compiler. That is, most compilers convert source code into a runnable program in three steps. First, a lexer module groups characters into words or tokens that the compiler recognizes -- a process known as tokenizing. A second module, called the parser, analyzes groups of tokens in order to recognize legal language constructs. Last, a third module, the code generator, takes a set of legal language constructs and generates executable code. Sometimes, parsing and code generation are intermixed.
To use XML data in a Java program, we must undergo a similar process. First, we analyze every character in the XML text in order to recognize legal XML tokens such as start tags, attributes, end tags, and CDATA sections.
Second, we verify that the tokens form legal XML constructs. If an XML document consists entirely of legal constructs per the XML 1.0 specification, it is well-formed. At the most basic level, we need to make sure that, for instance, all of the tagging has matching opening and closing tags, and the attributes are properly structured in the opening tag.
Also, if a DTD is available, we have the option to make sure that the XML constructs found during parsing are legal in terms of the DTD, as well as being well-formed XML.
Finally, we use the data contained in the XML document to accomplish something useful -- I call this mapping XML into Java.
XML Parsers
Fortunately, there are off-the-shelf components -- XML parsers -- that perform some of these compiler-related tasks for us. XML parsers handle all lexical analysis and parsing tasks for us. Many currently available Java-based XML parsers support two popular parsing standards: the SAX and DOM APIs.
The availability of an off-the-shelf XML parser may make it seem that the hard part of using XML in Java has been done for you. In reality, applying an off-the-shelf XML parser is an involved task.
SAX and DOM APIs
The SAX API is event-based. XML parsers that implement the SAX API generate events that correspond to different features found in the parsed XML document. By responding to this stream of SAX events in Java code, you can write programs driven by XML-based data.
The DOM API is an object-model-based API. XML parsers that implement DOM create a generic object model in memory that represents the contents of the XML document. Once the XML parser has completed parsing, the memory contains a tree of DOM objects that offers information about both the structure and contents of the XML document.
The DOM concept grew out of the HTML browser world, where a common document object model represents the HTML document loaded in the browser. This HTML DOM then becomes available for scripting languages like JavaScript. HTML DOM has been very successful in this application.
Dangers of DOM
At first glance, the DOM API seems to be more feature-rich, and therefore better, than the SAX API. However, DOM has serious efficiency problems that can hurt performance-sensitive applications.
The current group of XML parsers that support DOM implement the in-memory object model by creating many tiny objects that represent DOM nodes containing either text or other DOM nodes. This sounds natural enough, but has negative performance implications. One of the most expensive operations in Java is the new operator. Correspondingly, for every new operator executed in Java, the JVM garbage collector must eventually remove the object from memory when no references to the object remain. The DOM API tends to really thrash the JVM memory system with its many small objects, which are typically tossed aside soon after parsing.
Another DOM issue is the fact that it loads the entire XML document into memory. For large documents, this becomes a problem. Again, since the DOM is implemented as many tiny objects, the memory footprint is even larger than the XML document itself because the JVM stores a few extra bytes of information regarding all of these objects, as well as the contents of the XML document.
It is also troubling that many Java programs don't actually use DOM's generic object structure. Instead, as soon as the DOM structure loads in memory, they copy the data into an object model specific to a particular problem domain -- a subtle yet wasteful process.
Another subtle issue for the DOM API is that code written for it must scan the XML document twice. The first pass creates the DOM structure in memory, the second locates all XML data the program is interested in. Certain coding styles may traverse the DOM structure several additional times while locating different pieces of XML data. By contrast, SAX's coding style encourages locating and collecting XML data in a single pass.
Some of these issues could be addressed with a better underlying data-structure design to internally represent the DOM object model. Issues such as encouraging multiple processing passes and translating between generic and specific object models cannot be addressed within the XML parsers.
SAX for survival
Compared to the DOM API, the SAX API is an attractive approach. SAX doesn't have a generic object model, so it doesn't have the memory or performance problems associated with abusing the new operator. And with SAX, there is no generic object model to ignore if you plan to use a specific problem-domain object model instead. Moreover, since SAX processes the XML document in a single pass, it requires much less processing time.
SAX does have a few drawbacks, but they are mostly related to the programmer, not the runtime performance of the API. Let's look at a few.
The first drawback is conceptual. Programmers are accustomed to navigating to get data; to find a file on a file server, you navigate by changing directories. Similarly, to get data from a database, you write an SQL query for the data you need. With SAX, this model is inverted. That is, you set up code that listens to the list of every available piece of XML data available. That code activates only when interesting XML data are being listed. At first, the SAX API seems odd, but after a while, thinking in this inverted way becomes second nature.
The second drawback is more dangerous. With SAX code, the naive "let's take a hack at it" approach will backfire fairly quickly, because the SAX parser exhaustively navigates the XML structure while simultaneously supplying the data stored in the XML document. Most people focus on the data-mapping aspect and neglect the navigational aspect. If you don't directly address the navigational aspect of SAX parsing, the code that keeps track of the location within the XML structure during SAX parsing will become spread out and have many subtle interactions. This problem is similar to those associated with overdependence on global variables. But if you learn to properly structure SAX code to keep it from becoming unwieldy, it is more straightforward than using the DOM API.
Basic SAX
There are currently two published versions of the SAX API. We'll use version 2 (see Resources ) for our examples. Version 2 uses different class and method names than version 1, but the structure of the code is the same.
SAX is an API, not a parser, so this code is generic across XML parsers. To get the examples to run, you will need to access an XML parser that supports SAX v2. I use Apache's Xerces parser. (See Resources .) Review your parser's getting-started guide for specifics on invoking a SAX parser.
The SAX API specification is pretty straightforward. In includes many details, but its primary task is to create a class that implements the ContentHandler interface, a callback interface used by XML parsers to notify your program of SAX events as they are found in the XML document.
The SAX API also conveniently supplies a DefaultHandler implementation class for the ContentHandler interface.
Once you've implemented the ContentHandler or extended the DefaultHandler , you need only direct the XML parser to parse a particular document.
Our first example extends the DefaultHandler to print each SAX event to the console. Th
Read
Tutorial at: Click here to view the tutorial
Rate Tutorial: Mapping XML to Java, Part 1 - JavaWorld August 2000
View Tutorial: Mapping XML to Java, Part 1 - JavaWorld August 2000
Related
Tutorials:
|
Displaying 1 - 50 of about 4239 Related Tutorials.
|
JDO UNPLUGGED - PART 1
Relational Mapping' Technology
developed by Java Community Process(JCP), with active... their own mapping between the relational data
model and their java object model...
extensions or mapping flexibility of the best Java Data Object (JDO)
solutions |
Set the mapping name
Set the mapping name
Set the mapping name ...;
3. Set the mapping name to the action attribute... for multiple action mappings. The attribute of the action mapping can be added |
JDO UNPLUGGED - PART II
JDO - Java Data Objects Tutorials, JDO Java Data Object, JDO Tutorial, JDO UNPLUGGED - PART II
JDO UNPLUGGED - PART II... www.jcp.org and selecting JSR-12 or
can be downloaded from sun java website. Goto |
Understanding Hibernate O/R Mapping
are simple xml documents.
Here are important elements of the mapping file:.
<...
Understanding Hibernate O/R Mapping
Understanding Hibernate O/R Mapping
  |
Hibernate Mapping
.
Hibernate uses xml file to define the O/R mapping in
the applications. But programmers....
In this tutorial we will use xml file defining
object/relational mapping...
Hibernate Mappings, Hibernate Mapping, Hibernate Mapping tutorial,
Hibernate |
Hibernate Mapping
.
Hibernate uses xml file to define the O/R mapping in
the applications. But programmers....
In this tutorial we will use xml file defining
object/relational mapping...
Hibernate Mappings, Hibernate Mapping, Hibernate Mapping tutorial,
Hibernate |
XML Books
;
Processing XML with Java
Welcome to Processing XML with Java, a complete tutorial about writing Java programs that read and write XML... the XML part of the technical book publishing industry, as well as a monster thread |
Hibernate Mapping Files
Hibernate Mapping Files, Hibernate Mapping File, Required Hibernate
Mapping Files to create applications
Hibernate Mapping Files...;
Hibernate Mapping Files:
In this section I |
String Exercises 1 - Answers
Java: String Exercises 1 - Answers
Java: String Exercises 1 - Answers
Answers to the String Exercises 1.
3 -- s refers to exactly the same string as a.
ERROR -- t |
Create XML File using Servlet
Created Successfully'.
JAXP (Java API for XML Processing) is a Java...
Create XML File using Servlet
Create XML File... xml file
using Servlet We have created file XmlServlet.java. |
JSTL XML Tags
- JSTL
&
SQL-TAGS
Tutorial
Home |
Part
1 | Part 2... |
Part
1 | Part 2 | Part
3 | Part 4
 ...
JSTL XML Tags
JSTL XML Tags
  |
WEBSERVICE USING APACHE AXIS - TUTORIAL-2 AXIS FOR EJB-WEBSERVICE (part-5)
had seen parts 1 to 4 of this tutorial on exposing an EJB as XML-Webservice using Axis. This is a 7 part
article.?
part-1 : Overview
part-2 : deploying...-bean
itself)
??????????????? a) java:RPC
????????????? ??b) java:EJB
?part-6 |
Java XML Books
, Part 2
In this second part in a several part series on XML for Java.... The java.xml.parsers package is part of the Java API for XML Processing (JAXP...
Java XML Books
Java XML Books
  |
Java Virtual Machine(JVM)
of Java architecture and it is the part of the JRE (Java Runtime Enviroment... to run. JVM is a part of Java Run Time Environment that is required by every... environment, it is impossible to run Java software. JVM forms the part |
A Java Persistence Example
for the management of the persistent data and
object/relational mapping. Java Persistence...
is a lightweight framework based on POJO for object-relational mapping. Java
language metadata annotations and/or XML deployment descriptor is used for the
mapping between |
Eclipse Plunging/XML
;
XMLEspresso
Built in catalog for creating XML Schema, WSDL, XSL, Java EE...
Eclipse Plunging/XML
Eclipse Plunging/XML...;
XMLBuddy
XMLBuddy XML editor. Supports content assist |
New Page 1
and use application data without using java code. EL
was introduced in JSTL 1.0... be a map key.. If the
first value is a Java Bean, then second value must be a bean... one is ${bigFive[0]}
The second one is ${bigFive["1"]}
EL Operators |
Stored Data in XML File using Servlet
and display a message 'Xml
File Created Successfully'.
JAXP (Java API for XML...
Stored Data in XML File using Servlet
Stored Data in XML File using Servlet
  |
Persistence O/R Mapping Plug-Ins For Eclipse
Persistence O/R Mapping Plug-Ins For Eclipse
Persistence O/R Mapping Plug-Ins For Eclipse
 ... deployment of
high-performance, custom applications written in Java, C++ or C |
Simple Linked List Exercise 1
Java: Simple Linked List Exercise 1
Java Notes: Simple Linked List Exercise 1
Name... strings and puts
them in a doubly linked list.
1
2
3
4
5
6 |
JFreeChart - An Introduction
java chart library.
David Gilbert founded the JFreeChart project in February 2000... layout managers
serialization utilities
a date chooser panel
XML parser |
Create - XML File (Document)
Java Create XML File,Java Create XML Document,Create XML Java,Create XML Files
Create - XML File (Document)
 ...\xml>java CreatXMLFile
Enter number to add elements in your XML file: 3 |
Java Persistence API
of the
persistent data and object/relational mapping. Java Persistence API is added in Java EE... mapping facility to manage relational data in java application. The
Java Persistence API contains the following areas:
Java Persistence API
O-R mapping |
XML Well-Formed-ness
XML Well Formedness,XML Well Formed,XML Well Formed Checker,Java XML DOM Parser,Java XML DOM Parser Example,Java XML DOM Example... DOMParserCheck.java
C:\vinod\xml>java DOMParserCheck
Enter File |
XML Interviews Question page9
) in the XML source:
1. the first child object is the element containing the question..., because it is an architecture, not an application, so it is not part of XML's job...
XML Interviews Question page9,xml Interviews Guide,xml Interviews |
Mapping MySQL Data Types in Java
JDBC Data Type Mapping,Data Type Mapping,Mapping MySQL Data Types in Java
Mapping MySQL Data Types in Java
 ....
The following table represent the default Java mapping
for various common MySQL data types |
Getting all XML Elements
Java XML Example,Java XML Element,XML Elements,Get XML Element
Getting all XML Elements
 ...\xml>javac DOMElements.java
C:\vinod\xml>java DOMElements |
XML Interviews Question page19
XML Interviews Question page19,xml Interviews Guide,xml Interviews
XML Interviews Question page19
 ... are special attributes used to declare XML namespaces?
I don't know the answer |
XML Parsers
XML Parsers
XML Parsers
 ...;
XML parser is used to read, update, create and manipulate
an XML document.
Parsing XML |
Java Interview Questions - Page 2
:
1. The Java Virtual Machine (Java VM)
2. The Java... is the package?
Answer: The package is a Java namespace or part of Java...
Java Interview Questions,interview questions java
Java |
Java get XML File
Java get XML File
Java get XML File...;
In this section, you will study how the java application read the XML file.
For this, you need to create a XML file.
Here is the employee.xml file |
XML Error checker and locater (DOM)
XML Error Checker,Java XML Example,Java XML Dom Examples,XML Error Messages
XML Error checker and locater (DOM)
 ...:\vinod\xml>java DOMLocateError
Enter File name: Employee-Detail1.xml |
Show output as a xml file using Velocity
Show output as a xml file using Velocity
Show output as a xml file using Velocity
 ... output as a xml file in velocity. The method
used in this example  |
Retrieving XML Data Using GWT
Retrieving XML Data Using GWT
Retrieving XML... XML file
Data from the server using GWT. The basic building
block for running...:-Create a java File named SimpleXML.java.
Put this File in the package |
XML: An Introduction
XML
XML: An Introduction
 ... is XML?
"XML is a cross-platform, software and
hardware independent tool for transmitting information"
XML is a W3C Recommendations. It
stands |
XML Tutorials
shift a beginner to XML-Java programming. In these tutorials we have
developed example programs using Java XML processing APIs. Tutorial starts.... Here we are providing many examples to help you master using XML
with Java |
XML Tutorials
shift a beginner to XML-Java programming. In these tutorials we have
developed example programs using Java XML processing APIs. Tutorial starts.... Here we are providing many examples to help you master using XML
with Java |
Developing Axis Web services with XML Schemas.
XML Schema and WSDL .
1. Define XML Schema ( Stock.xsd ). You can find...
Developing Axis Web services with XML Schemas
Developing Axis Web services with XML Schemas |
Create XML file from flat file and data insert into database
an XML and data insert into the database.
Step:1...
Create XML file from flat file and data insert into database
Create XML file from flat file and data insert into database |
Common Interview Questions Page -1
Common Interview Questions Page -1
Common Interview Questions Page -1
 ...;
Question:1. Tell Me a Little |
Getting Dom Tree Elements and their Corresponding XML Fragments
Java XML DOM Example,XML Fragments,Getting Dom Tree Elements and their Corresponding XML Fragments
Getting Dom Tree Elements... DisplayElementNodes.java
C:\vinod\xml>java DisplayElementNodes
Enter a XML file |
Java Interview Questions - Page 1
Java Interview Questions,interview questions java
Java Interview Questions - Page 1
 ...;
Java Interview |
An Overview of the XML-APIs
.
JAXP: Java API for XML Processing
This API provides a common interface...
Java objects as XML (marshalling) and for creating Java objects
from... XML-based data.
JAXM: Java API for XML Messaging
The JAXM API |
Designing XML Schema
Designing XML Schema
Designing XML Schema...;
XML documents can have a reference to a DTD or to an
XML Schema.
A Simple XML Document
Look |
String Exercises 1
Java: String Exercises 1
Java: String Exercises 1
Name...()
__________ 1 + a
__________ a.toUpperCase()
__________ "Tomorrow".indexOf |
Open Source XML Editor
Open Source XML Editor
Open Source XML Editor
Open
source Extensible XML Editor
The Xerlin Project is a Java? based XML modeling application written to make creating and editing XML files easier. It runs |
XML Attributes
XML Attributes
XML Attributes...;
XML... information that is not a part
of the data. In the example below, the file type |
Constructor Chaining Exercise 1
Java: Constructor Chaining Exercise 1
Java NotesConstructor Chaining Exercise 1
Name _______________________________
The first line of every constructor must be either |
Use of Core XML tags in JSP
. There
are three tags in this Core XML tag set.
1. <x:out> :
This tag... to show parsed
data of an XML file "user.xml".
1. user.xml
<...Use of Core XML tags in JSP
Use of Core XML |
Testing EntityReferences in Xml
;
This Example gives you the way to test EntityReferences in an XML file. JAXP (Java...
Testing EntityReferences in Xml,XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials
Testing EntityReferences in Xml |
|
|
|