Since the birth of XML, it has been one of the focus topics in the industry. After several years of development, the XML technology has become increasingly mature, and more applications are developed based on XML. Today, with the increasing popularity of the Internet, distributed programming is becoming increasingly important, and more applications are beginning to transform in this direction. In this field, XML, as an intermediate data interface, has shown its irreplaceable importance. At the same time, the potential of developing Internet distributed applications using Java language has become more and more promising, and the EJB architecture has become increasingly mature. With Java, people can quickly develop portable, flexible, and easy-to-manage distributed applications.
Java has always been regarded as one of the most suitable languages for XML programming. Java, a platform-independent language, and platform-independent data XML, can indeed complete the most complex and flexible distributed applications.
It is not difficult to introduce XML into Java applications. Many standards and libraries have been developed to simplify XML programming in Java. Among these specifications, the most popular ones are Sax and Dom, which are also the standards recommended by W3C. Java class libraries that support XML are even more numerous. Apart from the jxap released by Sun, there are similar products provided by giants such as IBM and Microsoft. In addition, most of these products are free of charge and do not spend any money on them. All these specifications and class libraries have greatly simplified the complexity of XML programming. You only need to understand these specifications and the APIS defined by jxap, XML programming is now available. The purpose of this article is to introduce these specifications and APIs. I believe that after reading this article, you will no longer think of XML programming as difficult.
Background
There have been a lot of discussions about XML, and their views on XML are also benevolent. It is very difficult to give an exact definition of XML, But we can look at the following four aspects:
1. XML is a markup language designed to spread over the Internet conveniently. XML is compatible with SGML (specifically a simplified subset of SGML) and can be easily browsed and edited in any text editor.
2. XML is used to define the logical structure of data and organize all the data in a tree, which makes it easy for XML documents to understand and process. The structure of an XML document is pre-defined by DTD or schema, which enables the data in XML to have a definite meaning in a specific application.
3. XML is a strictly defined language, which almost does not define any optional features. This maximizes the versatility of XML. Any XML-compatible parser can parse a legal XML document without any errors. In this way, XML can be used as a medium in the most broad sense and circulated in various platforms, languages, and programs.
4. XML is a syntax used to define data and original data, which enables you to define the data itself. This is also one of the most important features of XML, Because theoretically, everything can be traced using data. That is to say, because XML provides a method to describe data, it is capable of describing anything.
For the XML application, let's take a simple example to see its power.
Most websites are currently written in HTML. The well-designed web pages by web designers can be beautifully displayed in Web browsers, but if you want to redesign the content contained in these web pages in a book, it is clear that, the beautiful content on the browser cannot be easily reflected in the book. As we know, HTML is a poorly structured language that closely integrates display and content. It is very difficult to separate content from HTML files with choices, especially on well-designed web pages. At this time, perhaps the only way is to re-design. However, the emergence of XML provides a good solution to solve this problem.
Because XML only defines data and does not care about how data is displayed, the content and display of Websites designed with XML are separated. Generally, a webpage is generated after the given XML document is transformed using XSLT. Now we want to put the website content in a book. We only need to redefine XSLT and give the change rules, so that we can perfect the content in another form.
The above is just an important aspect of XML applications. In fact, XML applications are far more than that. Many protocols such as soap are based on XML.
The following content is specific XML programming. This article assumes that you have a certain understanding of the Java language (or other object-oriented language), so you will not go into details about the language.
Comparison of XML programming interfaces in Java: Dom sax JDOM JAXP
I. Dom (Document Object Model)
Defines a set of interfaces for the parsed versions of the XML document. The parser reads the entire document, constructs a memory-resident tree structure, and then the code can use the DOM interface to operate on this tree structure.
Advantage: the entire document tree is in the memory for ease of operation. It supports multiple features such as deletion, modification, and rescheduling;
Disadvantages: transferring the entire document to memory (including useless nodes) wastes time and space;
Usage: once the document is parsed, the data needs to be accessed multiple times;
Sufficient hardware resources (memory and CPU)
Ii. Sax
To solve Dom problems, the following occurs.
Event-driven. When the parser finds the start, end, text, start, or end of an element, it sends events and programmers write code to respond to these events and save data.
Advantage: the entire document does not need to be transferred in advance, which consumes less resources;
The code of the SAX Parser is smaller than that of the DOM parser. It is suitable for Applet and download.
Disadvantage: it is not persistent. After an event, if no data is saved, the data will be lost;
Stateless; only the text can be obtained from the event, but I do not know which element the text belongs;
Usage: applet;
Only a small amount of content in the XML document is required, and few requests are returned;
Low machine memory;
Iii. JDOM
To reduce the Dom and sax encoding volumes, JDOM appears;
Advantage: The 20-80 principle greatly reduces the amount of code
Usage: simple functions to be implemented, such as parsing and Creation
Java program
However, at the underlying layer, JDOM still uses SAX (most commonly used), Dom, and xanan
Iv. Japan
Provides unified programming interfaces for multiple XML Parser
Change the parser without changing the code
Usage: If JDOM is not used, it is generally recommended to use japx to isolate the code from the implementation details of various Resolvers.
(1) Introduction of JDOM and comparison with jaxb
Java + xml = JDOM!
This is the goal of the JDOM designer. If you have used annoying sax or Dom to process XML, you will know why JDOM or jaxb is required. At this year's (2002) javaone conference, Jason Hunter, the main founder of JDOM, gave a wonderful speech about JDOM, entitled JDOM makes XML easy.
In that document, JDOM was compared with Dom, and I prefer to compare it with jaxb. Jaxb and JDOM are both developed to provide more convenient XML processing interfaces than Dom and sax in Java, and solve this problem through completely different approaches. JDOM is a tree operation similar to Dom. Jaxb generates Java code to access the XML document through the DTD and binding mode, and maps the XML into a Java object for operation. You can decide which one to use based on your project needs and personal preferences.
Compared with jaxb, JDOM has the following characteristics:
1) JDOM is easier to use than jaxb. To use jaxb, you must first write the DTD and then write the binding mode. JDOM does not have such requirements. If you use Java and XML, you can even use JDOM simply by reading JDOM javadoc documents.
2) After compiling the DTD and binding mode in jaxb, the XML document is mapped to a Java object, and its data is the attribute of the Java object, and the data type is converted. Therefore, accessing XML documents is easier than JDOM.
3) The code generated by a DTD and binding mode in jaxb can only access the document restricted by this DTD. If you want to access other XML documents, you need to write a DTD and the binding mode. JDOM can process any XML document, including constrained and unrestricted.
Currently, neither JDOM nor jaxb has an official version. The latest version of JDOM is beta8, and jaxb is 1.0 early access. Its standard version is 0.21. Relatively speaking, JDOM is more mature. For example, jaxb does not support namespace and cannot write processing commands to XML documents. Sometimes the linefeeds and spaces we need to retain are automatically filtered out in jaxb, even placed in <! [CDATA [and]> cannot be spared. JDOM does not have these restrictions. If the above three points are determined by the characteristics of JDOM and jaxb and cannot be changed, it indicates that jaxb still needs more work.
(2) obtain and install JDOM
In the http://jdom.org, you can download the latest version of JDOM. Take JDOM beta8 as an example. After downloading and decompressing, The jdom jar file is the JDOM. jar file under the build Directory, which is added to the class path. In addition, JDOM also requires support for jar files such as xerces. jar in the lib directory. If the following error occurs during use:
Java. Lang. nosuchmethoderror
Or
Java. Lang. noclassdeffounderror: ORG/XML/sax/saxnotrecognizedexception
You need to ensure xerces. jar files are located in other XML classes such as JAXP or crimson in classpath. These class files, including older versions of xerces, may not support sax2.0 or DOM Level 2. As a result, the above error occurs.
(3) A simple example
The JDOM processing method is similar to Dom, but it is mainly implemented using sax, so you don't have to worry about processing speed and memory. In addition, there are almost no interfaces in JDOM, and all the classes are real classes without class factory classes. The most important package org. JDOM mainly has the following classes:
? Attribute
? CDATA
? Comment
? Doctype
? Document
? Element
? Entityref
? Namespace
? Processinginstruction
? Text
The XML document used for data input must use the org. JDOM. Input package, which in turn requires org. JDOM. output. As mentioned above, you can use it by reading the API documentation.
In our example, we read the XML file examplea. XML, add a Processing Instruction, modify the price and author of the first book, add an attribute, and write the file exampleb. xml:
// Examplea. xml
<? XML version = "1.0" encoding = "GBK"?>
<Booklist>
<Book>
<Name> JAVA Programming basics </Name>
<Author> Zhang San </author>
<Publishdate> 2002-6-6 </publishdate>
<Price> 35.0 </price>
</Book>
<Book>
<Name> application of XML in Java </Name>
<Author> Li Si </author>
<Publishdate> 2002-9-16 </publishdate>
<Price> 92.0 </price>
</Book>
</Booklist>
// Testjdom. Java
Import org. JDOM .*;
Import org. JDOM. Output .*;
Import org. JDOM. Input .*;
Import java. Io .*;
Public class testjdom {
Public static void main (string ARGs []) throws exception {
Saxbuilder sb = new saxbuilder ();
// Construct a document from the file. Because the encoding has been specified in the XML file, this is not required.
Document Doc = sb. Build (New fileinputstream ("examplea. xml "));
// Add a Processing Instruction
Processinginstruction Pi = new processinginstruction
("XML-stylesheet", "href =" booklist.html. XSL "type =" text/XSL "");
Doc. addcontent (PI );
Element root = Doc. getrootelement (); // obtain the root element.
Java. util. List books = root. getchildren (); // obtain the set of all child elements of the root element.
Element book = (element) books. Get (0); // obtain the first book element.
// Add an attribute for the first book
Attribute a = new attribute ("hot", "true ");
Book. setattribute ();
Element author = book. getchild ("author"); // obtain the specified word element.
Author. settext ("Wang Wu"); // change the author to Wang Wu
// Or text T = new text ("Wang Wu"); book. addcontent (t );
Element price = book. getchild ("price"); // obtain the specified word element.
// Modify the price. What is depressing is that we must convert the Data Type ourselves, which is the advantage of jaxb.
Author. settext (float. tostring (50366f ));
String indent = "";
Boolean newlines = true;
Xmloutputter outp = new xmloutputter (indent, newlines, "GBK ");
Outp. Output (Doc, new fileoutputstream ("exampleb. xml "));
}
};
Execution result exampleb. xml:
<? XML version = "1.0" encoding = "GBK"?>
<Booklist>
<Book hot = "true">
<Name> JAVA Programming basics </Name>
<Author> 50.0 </author>
<Publishdate> 2002-6-6 </publishdate>
<Price> 35.0 </price>
</Book>
<Book>
<Name> application of XML in Java </Name>
<Author> Li Si </author>
<Publishdate> 2002-9-16 </publishdate>
<Price> 92.0 </price>
</Book>
</Booklist>
<? XML-stylesheet href = "booklist.html. XSL" type = "text/XSL"?>
By default, the gettext () method of the element class of JDOM does not filter blank characters. If you need to filter, use settexttrim ().
(4) References
1) JDOM makes XML easy (http://www.servlets.com/speaking/jdom-javaone.pdf)
2) the Java & #8482; architecture for XML binding User's Guide (http://java.sun.com/xml/jaxb/jaxb-docs.pdf)
3) Web Services made easier. The Java TM APIs and ubuntures for XML, a technical White Paper (http://java.sun.com/xml/webservices.pdf)
When to use dom
--------------------------------------------------------------------------------
If your XML document contains document data (for example, framemaker documents stored in XML format), Dom is the most natural choice for your solution. If you want to create a system similar to document information management, You have to process a large amount of document data. Datachannel Rio is an example of indexing and organizing information in various types of document resources (such as Word and Excel files ). In this case, Dom is a very suitable program to access the information stored in these documents.
However, if you are mainly dealing with structured data (the serialized Java object in XML the equivalent of serialized Java objects in XML), Dom is not the best choice. That is what is appropriate for Sax.
When to use SAX
--------------------------------------------------------------------------------
If the information in your XML document is machine-readable (and machine-generated) data, Sax is a suitable API for you to access this information. Machine Readable and generated data types include the following:
Java object attributes saved in XML format
Queries expressed by text-based Query statements (SQL, xql, oql)
Result set generated by the query (this may contain data encoded into XML in the relational database table ).
In this case, the data generated by the machine is the data structure and class information that you generally need to generate in Java. A simple example is the address book containing personal information, as shown in. Unlike the word processor document, the XML file in this address book is an XML file that contains pure data that has been encoded into text.
When your data is in this style, you need to create your own data structures and classes (object models) to manage and continuously Save the data. Sax allows you to quickly create a processor class that can generate your object model instance. One example is a sax document processor. It reads XML documents containing the address book information and creates an addressbook class that can access the information. The sax guide tells you how to do this. This address book XML file contains the person element, and the person element contains the name and email elements. My addressbook object model includes the following classes:
Addressbook class, the person object container
Person class, string-type name and email container
In this way, my "Sax Address Book document processor" can convert the person element into the person object, and then store them into the addressbook object. This document processor converts the name and email elements into string objects.