Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating Java Classes dynamically from an XML document

Consider this scenario: I've an XML file called person.xml with the following data in it.

<person>
    <name>MrFoo</name>
    <age>28</age>
</person>

If I want to read this XML into a Java object, I would be creating a Java bean called PersonBean (with getters/setters for the attributes) as:

class Person{
    String name;
    int age;
}

And I could use any APIs for reading the XML and populating the Java Bean.

But the real question here is, suppose if the structure of the XML file changes, i.e. if an new attribute 'email' is added to the XML file, then I have to modify the Java Bean also to add a new attribute. But, I want to avoid changing the Java code even if the XML structure changes.

So, what I'm trying to do is, I'm creating another XML file called PersonStructure.xml with the content as:

<class name="Person">
  <attributes>
      <attribute>
          <name>personName</name>
          <type>java.lang.String</type>
      </attribute>
      ... and it goes like this...
   </attribute>
</class>

Is it possible to read the PersonStructure.XML file and convert it into Person.Java class file? The approach what I'm trying to do is correct or is there any other way to do the same?

like image 536
Veera Avatar asked May 08 '09 09:05

Veera


People also ask

Can we create dynamic class in Java?

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.

Can we write Java code in XML file?

Java Architecture for XML Binding (JAXB) is a Java standard that allows to convert Java objects to XML and vice versa. JAXB defines a programmer API for reading and writing Java objects to from XML documents.

Does XML have classes?

Studio provides a wizard that reads an XML schema (from a file or URL) and generates a set of XML-enabled classes that correspond to the types defined in the schema. All the classes extend %XML.

What is dynamic XML?

By dynamic XML we mean the content that is created as a function of request parameters or state of the requested resource. For this reason, a lot of work and design has been put into Cocoon to allow dynamic XML content to be generated.


1 Answers

While this is not exactly what you are trying to do, you should have a look at JAXB. It can generate a set of Java classes from a Schema definition. Your PersonStructure.xml file looks quite a bit like an XSD with a different syntax, so you could reuse JAXB.

https://jaxb.dev.java.net/

like image 71
Guillaume Avatar answered Sep 27 '22 21:09

Guillaume