Reputation: 37
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.
Upvotes: 0
Views: 1663
Reputation: 649
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
Upvotes: 1
Reputation: 31235
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
Upvotes: 0