Simple way to do Xml in Java

Is there is Simple way to read and write Xml in Java?

I've used a SAX parser before but I remember it being unintuitive, I've looked at a couple of tutorials for JAXB and it just looks complicated.

I don't know if I've been spoilt by C#'s XmlDocument class, but All I want to do is create an Xml Document that represents a a set of classes and their members (some are attributes some are elements).

I would look into serialization but the XML has to have the same format as the output of a c# app which I am reverse engineering into Java.

Answers


I recommend XOM. Its API is clear and intuitive.


You should check out Xstream. There is a 2 minute tutorial that is really simple. To get the same format, you would model the classes the same.


If you are using jdk 1.4 or newer take a look at XMLEncoder class.


Some of the more popular approaches to consider:

Java Archictecture for XML Binding

JAXB is a specification for a standard XML binding. If you already have an XSD, it can generate your Java classes for you, and then all that's left is to use a standard API for marshalling/unmarshalling.

  • Reference implementation from Glassfish
  • Apache's implementation JaxMe
Other binding approaches

As with JAXB, these approaches use XML-based binding configurations. They may provide more fine grained control of the unmarshalling process.

Roll your own

Dom4j is a simple api for creating xml documents in java.

Document document = DocumentHelper.createDocument();
Element root = document.addElement( "root" );

Element author2 = root.addElement( "author" )
  .addAttribute( "name", "Toby" )
  .addAttribute( "location", "Germany" )
  .addText( "Tobias Rademacher" );

The most simple way so far is the MarkupBuilder in Groovy. Think of Groovy as a new syntax for Java. The XmlSlurper can be used to read XML.


I think that Apache XMLBeans provides the functionality you are after.

The Wikipedia page gives a good overview and example usage.


There is a wide choice of XML processing options for Java, though judging from the .NET documentation for XmlDocument, the Java DOM implementation is the closest out-of-the-box equivalent.

.NET XmlDocument:

This class implements the W3C Document Object Model (DOM) Level 1 Core and the Core DOM Level 2.

Java Document:

See also the Document Object Model (DOM) Level 3 Core Specification.

Sample code:

public static void main(String[] args) throws Exception {
	File xmlFile = new File(".classpath");

	// read it
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = factory.newDocumentBuilder();
	Document document = builder.parse(xmlFile);

	// walk it
	System.out.println("Node count=" + countNodes(document));

	// write it
	Source source = new DOMSource(document);
	Result result = new StreamResult(System.out);
	TransformerFactory transformerFactory = TransformerFactory
			.newInstance();
	Transformer transformer = transformerFactory.newTransformer();
	transformer.transform(source, result);
}

/** Doesn't count attributes, etc */
private static int countNodes(Node node) {
	int count = 0;

	NodeList kids = node.getChildNodes();
	count += kids.getLength();
	for (int i = 0; i < kids.getLength(); i++) {
		count += countNodes(kids.item(i));
	}

	return count;
}

I think JAXB is only complicated if you look at wrong examples. Specifically, yes, schema-based way can get messy. But code-first, annotation-based is trivially easy.

Another easy alternative is XStream. And for non-binding case, StaxMate, which is an add-on for streaming Stax parsers.


If SAX parsing is mandatory, JAXP is a good choice. I prefer DOM parsing and use jdom which seems a lot easier to me.


I would certainly use XOM if you want a DOM-like approach and SAX (www.sax.org) if you want a SAX-like approach. I was involved in the early development of XML and SAX was developed as an event-driven approach, which is useful for some applications. DOM/XOM and SAX are complementary - sometimes you need one, sometimes the other. If you wish to build objects as you go rather than read everything into memory, use SAX. If you are happy to read everything in and then process it, use XOM.

I spent far too much time trying to get the W3C DOM to work - IMO it is poorly defined with too many ways of doing some things and not enough for others. When XOM came it revolutionised my productivity.

The XOM community is very knowledgeable and focused and helpful.


Need Your Help

“No visible @interface for 'NSData' declares the selector 'base64EncodedString” error in MKStoreKit

objective-c cocos2d-iphone

I'm trying to upgrade my MKStoreKit to version 4.0 in my app so I can incorporate the "restore in app purchase" feature into my app. Apple wants to reject my app due to this missing feature. I've b...