Use Java to generate xml

Source: Internet
Author: User
Generally, when we mention XML, most problems will be resolved in XML and XML structures. In this field of technology, W3C proposed Dom and sax specifications to parse data. Sun provides Java XML pack, while Apache releases xerces and xalan. However, there is almost no focus on the XML output. There are some projects that convert JavaBeans and swing components into XML, but in most cases, developers only want to output data structures in a custom format, which is not difficult.

This article specifically discusses some methods for creating XML documents through Java. I will specifically mention several solutions for creating XML documents using Java. They all have different advantages, some of which are simple and some depend on some powerful class libraries. Let me start with the simplest method.
Use the stringbuffer class
The simplest and most common method for creating XML documents is to create one by yourself. You can use the stringbuffer class or some writer classes. The advantage is that you do not need to use other libraries or create additional objects. However, this action also brings many disadvantages. The first challenge is the inability to ensure the correctness of the XML format. Characters must be carefully considered when placed into the string object. You must be especially careful with the appearance of XML entities, such as replacing with <. Listing a provides an example.

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

In this simple example, if the name is odd, such as Jon "The Cat" Smith, the output format will go wrong. This Code does not process quotation marks when obtaining the name. The code output from the result is as follows. Obviously, this representation is incorrect:
<Person name = "Jon" The Cat "Smith" age = "21"/>

When reading the source code, it is difficult to trace the XML hidden in Java. To put it another way, about half of the errors in such development measures are attributed to the absence of closed tags and quotation marks for error processing. In short, the XML format is invalid.
More explicit and simple method: Dom
The first method is Dom, which is the so-called Document Object Model ). After an object structure is given, you can convert it to an XML object structure in a certain format and then output the result. There are many available structure types, including the XML class of the Jakarta Element construction kit (ECS) project to a parser that fully complies with Dom specifications, such as xerces, usually, the smaller the version, the simpler the XML output method. List B is an example of using ECS.

Listing B provides a concise method for outputting data. In fact, you can combine two output rows into one by attaching the output method to the new xmldocument. This is a kind of ECs-like syntax mode, which is very convenient to use. However, this method does not provide if-null protection for age replication. To implement this protection, you must use the code in listing C.

ECS has several advantages, so you do not need to avoid quotation marks ("). 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. The W3C Dom, JDOM, or dom4j is more complex to process this style of code. Of course, W3C Dom still has the advantages of independent parsing.

Disadvantages of XML output using ECs include the problems caused by objects. You must create an object before writing the content. This is good in most cases, but you do not want to create this XML structure when outputting large XML files. The same problem exists for most other dom methods.

Compared to simply using the writers or stringbuffer class, ECs is quite similar to a tag. It is large in size, but only a small part of it is used to output XML. The biggest problem is that it has little room for activity. It beat other schemes of the same type, because other types are larger, bulky, and more complex.
Sax
SAX (Simple API for XML) can replace dom-style XML parsing. It consists of a series of events or callback functions called by code when parsing XML files. When you output the result directly to strings, it won't be very useful. However, it can be used in indirect and more complex ways.

The code that outputs strings can be used to output a sax event. This method is much higher than just outputting strings. It can be added to a simple base class to convert the sax event to XML.

Let's take a look at the example below. The example uses the following classes:
• Person: Business Object. previously described
• Personinputsource: accepts the person object
• Personxmlreader: knows how to convert personinputsource to a sax event
• Xmlprettyprinter: converts a sax event to a contenthandler in XML.

The most important code is in personxmlreader, as shown in listing D.

The code in listing D illustrates how the person object is converted to a series of sax events. But this is not the simplest task. Converting person to XML using Sax is implemented through the code in listing E.

Using sax clearly gives you powerful computing capabilities, because you can attach a SAX Parser to XML instead of xmlprettyprinter. However, adding a processor also increases complexity. Sax is a more complex concept. In most cases, a simple method usually works best.

Once the basic components are compiled (xmlprettyprinter is a basic inputsource and xmlparser object), generating events is a trivial matter. To output a New XML structure, you only need to use the parse method and insert the component.

Setting up XML around a sax event is not a quick and convenient measure.
Xmlwriter class
Finally, I propose my own solution, which is the xmlwriter class. My idea is to use a technology that is too simple and too complex to output XML.

Important design requirements are as follows:
• Encapsulate java. Io. Writer
• Writer APIs
• Process XML as much as possible
• Avoid creating large object structures
• ECs chain style is allowed

To meet these requirements, you can write XML into two styles. First, it can be written in Java. Lang. Writer code, as shown in list f.

Second, it can be written in the encoding style of the chained method, which is similar to that of ECs, because each write method returns the xmlwriter itself. Listing G provides such an example.

From the perspective of performance, xmlwriter has some significant advantages, and almost no other objects are created. It has considerable functionality and can process basic XML fragments (but there is no comment, contraction, or document type ). The most important thing is that it is easy to use.

Negative issues have been mentioned, and it cannot process annotations, indentation, or document types. ECS can close tags when writing XML objects. xmlwriter needs to call the endentity method. If the object is not terminated, the xmlwritingexception will be thrown when this method is called. Finally, there is a close method. It does not close the writer object, but will complete XML in any writing. Perhaps most importantly, it will throw xmlwritingexception without terminating the object.
Summary
There are several ways to generate xml methods. Xmlwriter is not necessarily the best XML creation tool, but this method fills the gap between being too simple, too cumbersome, or even 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.