File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes XML and Related Technologies and the fly likes Create a XML file in Java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » XML and Related Technologies
Bookmark "Create a XML file in Java" Watch "Create a XML file in Java" New topic

Create a XML file in Java

Miguel Roque
Ranch Hand

Joined: Oct 24, 2002
Posts: 126

I need to export some data from a DB to a XML file but I've never worked with XML in Java so I need your help. First of all, what is the best thecnology to use? I've seen JAXB, SAX, DOM and some others, but I don't know where to start here and what will be the best one to use.

In order to create the XML, I must follow the rules from a xsd file and the created XML will have several sections created, each of the sections being retrieved from a different table/tables.

Venkata Kumar
Ranch Hand

Joined: Apr 16, 2008
Posts: 110

SAX is not suitable to create XML document as it doesn't allow manipulation of data in memory.

JAXB and DOM are useful to create XML documents. Building XML document using DOM API requires understanding the document tree structure and adding child nodes one after one which may be tedious.

JAXB API can be used to convert XML document into Java objects and vice versa. You can generate Java objects from xsd using binding compiler xjc provided by JAXB and load the Java objects with the data from database. Convert the objects into xml using JAXB API.

SCJP 5.0, SCWCD 5, preparing for SCDJWS
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13035
You could also treat this as a problem of writing a formatted text file where the format required is valid XML conforming to a schema.

No XML library need be involved.

There are also cool tools such as ServingXML which can handle a wide variety of input formats and create XML.

Jimmy Clark
Ranch Hand

Joined: Apr 16, 2008
Posts: 2187
Typically, the "best" option for creating XML-based data files is to stay away from any "public" API such as DOM, SAX, JAXB, and create a custom API which is specific to the target markup language. Note that this applies for creating complex XML-based structures, not simple structures. Either DOM or JAXB can easily be used for the simple stuff

This option gives you the most degree of control and helps you avoid tightly coupling your code to a specific XML schema, i.e. do not attempt to use schema for "creating" XML-based files.
I agree. Here's the link:
subject: Create a XML file in Java
jQuery in Action, 3rd edition