Generating XML in Java

Source: Internet
Author: User
Tags data structures object model requires stringbuffer advantage
xml| generate XML in general, as soon as we mention XML, most of the problems are focused on parsing XML and XML structures. In this type of technology, the world's Business consortium proposes DOM and sax specifications to parse data, Sun provides Java XML packs, and Apache launches Xerces and Xalan. However, little attention has been paid to the problem of exporting XML. There are some projects that transform JavaBeans and swing components into XML, but in most cases developers simply want to output data structures in a custom format, a task that is not difficult.

This article specifically explores some of the ways to create XML documents through Java. I will specifically mention several scenarios for creating XML documents in Java. They all have different advantages, some are simple, others rely on some powerful class libraries. Let me start with the simplest way.
Using the StringBuffer class
The simplest and most common way to create XML documents is to do it yourself. You can use the StringBuffer class or some writer class. The advantage is that you don't need to use other libraries, and you don't have to create extra objects. However, this move also brings a lot of shortcomings. The first is the inability to guarantee the correctness of the XML format. Characters must be considered carefully when placing a string object. You have to be particularly careful about the appearance of XML entities, such as < instead of <. Listing a provides an example of this.

The output of program list A is:
<person name= "Jon Smith" age= "/>"

In this simple example, if the names are weird, like Jon "The Cat" Smith, the output format is problematic. This code does not handle quotes when it gets the name, and the resulting output code is the following, which is obviously wrong:
<person name= "Jon" the Cat "Smith" age= "/>"

It's hard to keep track of XML hidden in Java while reading the source code. In contrast, about 1 and a half of the errors in this development are attributed to the absence of closed tags and incorrect quotation marks, which in short form invalid XML.
A clearer and simpler approach: DOM
The 2nd option is DOM, the so-called Document Object model. After a given object structure, you can convert it to a form of XML object structure, and then output the result. There are many types of structures available, ranging from XML classes of Jakarta Element construction Kit (ECS) projects to parsers that fully comply with DOM specifications, such as Xerces, which, in general, are simpler ways to output XML in smaller versions. Listing B is an example of using ECS.

Listing B presents a concise approach to output data. In fact, you can combine two output lines into one, by attaching the output method to the new XmlDocument. This is a type of ECS with a class of grammatical patterns, it is very convenient to use. However, this method does not properly replicate If-null protection against the age of the person. In order to achieve this protection, you must take the code in Listing C.

ECS shows several advantages, and you don't have to avoid the quote character ("). You do not need to completely close the tag, the object will do the work for you, any XML characters, such as < or > are replaced by < and >, ECS is the simplest Dom method. It is more complicated to use the DOM, Jdom, or dom4j of the consortium to deal with this style of code, of course, the DOM of the consortium still has the advantage of independent parsing.

The disadvantages of using ECS to output XML include the problem that the object leads to. You have to create the object before you write it. This is good in most cases, but you don't want to build this XML structure when you're exporting large XML files. The same problem exists for most other DOM methods.

ECS is quite close to a mark compared to simply using writers or stringbuffer classes. It has a large volume, but only a small portion of it is used to output XML. The biggest problem is that there is little scope for its activities. It beats other types of schemes because other types are bigger, heavier, and more complex.
Sax
SAX (simple APIs for XML) can replace DOM-style XML parsing. It consists of a series of events or callback functions that the code calls when parsing the XML file. It doesn't make much use if you output the results directly to strings. However, it can be used in indirect, more complex ways.

Output strings code can replace the output sax event. This is much higher than just the output strings, which can be added to a simple base class that converts SAX events into XML.

Let's take a look at the example below, which uses the following classes:
Person: Business object, previously explained
Personinputsource: Accepting the Person object
Personxmlreader: Know how to convert Personinputsource to sax events
Xmlprettyprinter: Converting sax events to XML ContentHandler

The most important of the code is in Personxmlreader, as shown in Listing D.

The code in Listing D shows how the person object is converted to a series of SAX events. But it's not the easiest job. Using Sax to convert person to XML is done through the code in Listing E.

Using sax obviously gives you a powerful computing power, because you can attach sax parsers to XML without using Xmlprettyprinter. However, adding complexity is also added to the processor, and SAX is a more complex concept. In most cases, simple methods tend to work best.

Once the basic components are written (Xmlprettyprinter is a basic InputSource, a Xmlparser object), generating events is a trivial matter. The output of the new XML structure requires only the parse method and the Insert component.

Building XML around Sax events is not a quick and easy measure.
Adopt XmlWriter Class
Finally I propose my own plan, this is the XmlWriter class. My idea is to use a technique that is too simple and too complex to output XML.

The important design requirements are as follows:
• Encapsulation Java.io.Writer
• Provides APIs for writer classes
• Process XML as much as possible
• Avoid building large object structures
• Allow ECS chain style

Implementing these requirements allows XML to be written in two flavors. First, it can be written in Java.lang.Writer code, as shown in Listing F.

Second, it can be written in the coded style of a chained method, which is similar to ECS because each write method returns XmlWriter itself. Listing G gives an example of this.

From a performance point of view, XmlWriter has some notable advantages, and it hardly creates other objects. is quite functional and can handle basic XML fragments (without annotations, indentation, or document types). The most important thing is that it's easy to use.

The negative issues have been mentioned, and it cannot handle annotations, indents, or document types. While ECS can close tags when XML objects write themselves, XmlWriter requires you to call the Endentity method. If the entity calls the method without terminating it throws a xmlwritingexception. Finally, there is a close method. It does not close the writer object, but completes any written XML. Perhaps most importantly, it throws out the xmlwritingexception when the entity is not terminated.
Summary
There are several ways to produce XML methods. XmlWriter is not necessarily the best XML creation tool, but it fills the gap between being too simple, too unwieldy, or too complex.



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.