Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to do XML in Java

Tags:

java

xml

groovy

There are a lot of questions that ask the best XML parser, I am more interested in what is the XML parser that is the most like Groovy for Java?

I want:

SomeApiDefinedObject o = parseXml( xml );
for( SomeApiDefinedObject it : o.getChildren() ) {
   System.out.println( it.getAttributes() );
}

The most important things are that I don't want to create a class for every type of XML node, I'd rather just deal with them all as strings, and that building the XML doesn't require any converters or anything, just a simple object that is already defined

If you have used the Groovy XML parser, you will know what I'm talking about

Alternatively, would it be better for me to just use Groovy from Java?

like image 554
walnutmon Avatar asked Apr 22 '10 19:04

walnutmon


2 Answers

Here is something quick you can do with Sun Java Streaming XML Parser

    FileInputStream xmlStream = new FileInputStream(new File("myxml.xml"));
    XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(xmlStream);
    while(reader.hasNext()){
        reader.next();
        for(int i=0; i < reader.getAttributeCount(); i++) {
           System.out.println(reader.getAttributeName(i) + "=" + reader.getAttributeValue(i));
        }
    }
like image 74
ring bearer Avatar answered Sep 24 '22 00:09

ring bearer


I would like to shamelessly plug the small open-source library I have written to make parsing XML in Java a breeze.

Check out Jinq2XML.

http://code.google.com/p/jinq2xml/

Some sample code would look like:

Jocument joc = Jocument.load(urlOrStreamOrFileName);
joc.single("root").children().each(new Action() {
    public void act(Jode j){
        System.out.println(j.name() + ": " + j.value());
    }
});
like image 41
jjnguy Avatar answered Sep 27 '22 00:09

jjnguy