Dilum Ranatunga
Dilum Ranatunga

Reputation: 13374

Reading and writing XML using JUST Java 1.5 (or earlier)

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?

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

Upvotes: 5

Views: 2600

Answers (2)

McDowell
McDowell

Reputation: 108859

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).

Upvotes: 5

Jason Cohen
Jason Cohen

Reputation: 83001

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/>.

Upvotes: 0

Related Questions