views:

487

answers:

3

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?

+6  A: 

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/

Guillaume
You can also use XMLBeans which does nearly the same as JAXB http://xmlbeans.apache.org/
HaBaLeS
+4  A: 

Not very familiar with Java (I'm mostly a .NET guy), but common sense applies: there's actually very little use in dynamically generated beans (unless you'll be binding those to some control, in which case array of Objects will do just fine).

What is more logical is codegen'ing Java beans from this XML definitions, which can be done with XSLT.

PS. Do not try to make a programming language out of XML. Hell will definitely break loose if you do so.

Anton Gogolev
A: 

I am running through somehow more or less the same problem (I need to transform data in Java to a POM.xml file), one of the things that did not work for me, but maybe could work for you was the XStream library, it transforms java classes into xml, you should take a look:

http://xstream.codehaus.org/

I am in anyway related to them, just a random guy looking for his own answers. Should you have any questions about how to use this library you should try to contact them. Hope it solves your problem.

Random