Search code examples
javaxmlpojo

How to generate a pojo class ( in jvm) from a xml?


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.


Solution

  • 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.