Omar Kooheji
Omar Kooheji

Reputation: 55760

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.

Upvotes: 28

Views: 11393

Answers (11)

Kyle Dyer
Kyle Dyer

Reputation: 308

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" );

Upvotes: 3

peter.murray.rust
peter.murray.rust

Reputation: 38033

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.

Upvotes: 0

StaxMan
StaxMan

Reputation: 116472

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.

Upvotes: 1

McDowell
McDowell

Reputation: 108859

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;
}

Upvotes: 2

Kai Huppmann
Kai Huppmann

Reputation: 10775

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

Upvotes: 0

toolkit
toolkit

Reputation: 50227

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

Upvotes: 3

grayger
grayger

Reputation: 931

I recommend XOM. Its API is clear and intuitive.

Upvotes: 15

stephendl
stephendl

Reputation: 722

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

The Wikipedia page gives a good overview and example usage.

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328536

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.

Upvotes: 2

Marko
Marko

Reputation: 31375

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

Upvotes: 3

Milhous
Milhous

Reputation: 14643

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.

Upvotes: 8

Related Questions