tags:

views:

845

answers:

2

For reading XML, there is SAX and DOM built into Java 1.5. You can use JAXP and not need to know details about what parser is available... So, what are some prescribed APIs for one to write XML documents in Java 1.5 and earlier?

  • I don't want to use a third party binary
  • I don't want to assume a Sun VM or IBM VM etc and use some specialized class
  • Whatever means there is of writing the document, I would like to read in a complementary way.
  • Performance and suitability for large XML files is not particularly important

Ideally, a read-and-write with no changes is just a few lines of code.

A: 

There's no official "prescribed" API, but we've been very happy with the following technique:

Create a class XmlWriter that initializes with a character Writer and has methods like startElement( String name ), writeAttribute( String name, String value ), and writeCData( String text ).

Then implement in the obvious way. Internal methods can do things like SGML character escaping; see Apache Commons for utilities that will help.

If you want the output to be more human-readable, you can do things like track element nesting level and add newlines and tabs or spaces. Also optional is tracking things like an element being opened and closed without anything inside which can be abbreviated as <element/>.

Jason Cohen
+3  A: 

Java 1.4 comes with javax.xml.transform, which can take a DOMSource, SAXSource, etc:

// print document
InputSource inputSource = new InputSource(stream);
Source saxSource = new SAXSource(inputSource);
Result result = new StreamResult(System.out);
TransformerFactory transformerFactory = TransformerFactory
    .newInstance();
Transformer transformer = transformerFactory
    .newTransformer();
transformer.transform(saxSource, result);

If you want to go back to the J2SE 1.3 API, you're pretty much on your own (though if you're on the J2EE API of that era, there might be something - I don't recall).

McDowell
This exactly the right answer for the question I had typed up. But in hindsight the question is misleading. I want to create a bunch of new content; I am uncertain how one creates new content using a Transformer...
Dilum Ranatunga
I would start a new question with an example of the input data and the output you want to produce from it.
McDowell
Also, how to use a Transformer: http://java.sun.com/webservices/reference/tutorials/jaxp/html/xslt.htmlThough, it isn't clear whether you need all that.
McDowell