2

I am looking for different ways of parsing an XML document to Java objects.

I have an XML document, I need to parse this XML document to extract the elements and parse them in to Java objects.

Could you please recommend the following?

  • different approaches
  • productive parser tools for Java
halfer
  • 19,824
  • 17
  • 99
  • 186
olidev
  • 20,058
  • 51
  • 133
  • 197
  • Some similar questions: http://stackoverflow.com/questions/3276149/java-converting-xml-to-java-objects, http://stackoverflow.com/questions/3495336/is-there-a-declarative-way-to-parse-xml-to-java-objects – Mark May 10 '11 at 08:58

2 Answers2

2

try the solution given in this url http://www.developerfusion.com/code/2064/a-simple-way-to-read-an-xml-file-in-java/

A B
  • 1,926
  • 1
  • 20
  • 42
0

Personally I'll use Groovy program a simple XML parser of the XML document using XmlSlurper and returns a map as an interface.

Or just use the Groovy to return the value

class XmlParseHelper {
    private def xmlNode;

    private String elementName


    public XmlParserHelper(String elementName, String xml){
        this.elementName = elementName
        xmlNode = new XmlSlurper().parseText(xml)
    }

    public int getTotalRows(){
        return xmlNode.table.find{it.@name == elementName}.row.size()
    }


    public String getValue(String columName, int index){
        return xmlNode.table.find{it.@name == elementName}.row[index].column.find{it.@name == columnName}.toString()
    }
}

and can be used like this

//xml is the string of the xml
XmlParseHelper xmlParseHelper = new XmlParseHelper ("mytable", xml);

        for(int i = 0; i < XmlParseHelper .getTotalRows(); i++){
            String code= xmlParseHelper.getValue("code", i);
            String name= xmlParseHelper.getValue("name", i);
.....
     }

This was for an specific XML, but well: it's a different approach.

halfer
  • 19,824
  • 17
  • 99
  • 186
jjchiw
  • 4,375
  • 1
  • 29
  • 30