views:

1515

answers:

12

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.

+8  A: 

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.

Milhous
Be aware: XStream does not handle namespaces properly.
duffymo
duly noted, If the poster does not have namespace issues.
Milhous
I love XStream... so easy to use. Great for quick jobs when you need to save an object to xml and read it back in.
Bernie Perez
+2  A: 

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

Dev er dev
...and then the XMLDecoder to get your objects back!
oxbow_lakes
A: 

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

Kai
+2  A: 

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.

Aaron Digulla
+2  A: 

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

The Wikipedia page gives a good overview and example usage.

stephendl
+12  A: 

I recommend XOM. Its API is clear and intuitive.

grayger
See also: http://stackoverflow.com/questions/528312/creating-an-xml-document-using-namespaces-in-java/528512
toolkit
XOM ftw. It's far simpler than DOM or SAX for most cases. I only had to break out of XOM and use SAX once, for processing a huge document.
Marcus Downing
A while back I upvoted the dom4j answer, but after testing out XOM I'm starting to agree with this. To see why XOM might be better than dom4j (or JDOM, for that matter), check out http://stackoverflow.com/questions/831865/what-java-xml-library-do-you-recommend-to-replace-dom4j
Jonik
I'm struggling to use XOM, it's not intuitive for me.
Jonas
+2  A: 

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

toolkit
A: 

this page http://www.javazoom.net/services/newsletter/xmlgeneration.html contains IMHO the best ways to generate XML (methods 4 and 5)

chburd
+1  A: 

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;
}
McDowell
+3  A: 

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" );
Kyle Dyer
Link now goes to an unrelated website. Go here instead: http://dom4j.sourceforge.net/
BlairHippo
fixed the link. Thanks.
Kyle Dyer
A: 

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.

StaxMan
A: 

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.

peter.murray.rust