Question

I have a xml :

<Employee>
   <name>xyz</name>
   <age>50</age>
   <salary>111</salary>
</Employee>

now how can I create a class dynamically in jvm from this xml ?? How to create setter/getter for this class ?

NOTE:: In future these xml elements can increase.

Was it helpful?

Solution 2

Here is an example to parse your XML file with JDOM2

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;

public class Test {

  public static void main(String[] args) throws Exception {
    Document document = new SAXBuilder().build(Test.class.getResourceAsStream("test.xml"));

    for(Element elt :document.getRootElement().getChildren()) {
      System.out.println("tag : "+elt.getName());
      System.out.println("value : " + elt.getText()+"\n");
    }
  }
}

Output :

tag : name
value : xyz

tag : age
value : 50

tag : salary
value : 111

After that, you can

  • Store the values in a Map OR
  • Generate a .java file (I suggest to do it via Freemarker) and compile it.

OTHER TIPS

Usualy, java source files for XML binding are generated using some XML schema or DTD for expected data format.

In this case, proposal is to define XML schema, for example like this:

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
      targetNamespace="http://test.org/test/Employee">
<xsd:element name="employee">
    <xsd:complexType>
        <xsd:sequence>
            <xsd:element name="name" type="xsd:string" />
            <xsd:element name="age" type="xsd:integer" />
            <xsd:element name="salary" type="xsd:double" />
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

This schema.xsd can be used as input to the number of generators like JAXB (xjc command) or Castor, as shown here

Generator output is configurable, and new sources should be easy to integrate to existing project, or compile and load. This topic is discussed here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top