28

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.

Omar Kooheji
  • 54,530
  • 68
  • 182
  • 238

11 Answers11

15

I recommend XOM. Its API is clear and intuitive.

grayger
  • 931
  • 8
  • 19
  • 1
    See also: http://stackoverflow.com/questions/528312/creating-an-xml-document-using-namespaces-in-java/528512 – toolkit Feb 09 '09 at 16:07
  • 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 Feb 09 '09 at 16:17
  • 1
    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 Jun 07 '09 at 16:43
  • I'm struggling to use XOM, it's not intuitive for me. – Jonas Aug 18 '10 at 09:55
8

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
  • 14,473
  • 16
  • 63
  • 82
3

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

Marko
  • 30,263
  • 18
  • 74
  • 108
3

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
  • 49,809
  • 17
  • 109
  • 135
3

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
  • 308
  • 1
  • 4
2

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
  • 321,842
  • 108
  • 597
  • 820
2

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

The Wikipedia page gives a good overview and example usage.

stephendl
  • 722
  • 3
  • 9
2

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
  • 107,573
  • 31
  • 204
  • 267
1

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
  • 113,358
  • 34
  • 211
  • 239
0

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
  • 37,407
  • 44
  • 153
  • 217
0

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 Huppmann
  • 10,705
  • 6
  • 47
  • 78