Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse document by template in Java

Is there any ready-to-use java library that, given a template, can read an xml-file that complies with that template and parse its values into a Java class? Sort of the job velocity does but in the reverse direction.

For example, given the following template

<person>
  <name>${person.name}</name>
  <age>${person.age}</age>
</person>

and the input file

<person>
  <name>John</name>
  <age>20</age>
</person>

it could read its values into class

class Person {
    public String name;
    public Integer age;
}

UPDATE: The example above is meant to show the general idea and has nothing to do with the serialization. Real example can also have elements and attributes that correspond to the fields related to the different Java object and the input file can have structure which cannot be used to deserialize objects with the values located across different attributes of different XML elements. So it's not a serialization issue.

like image 761
koss Avatar asked Feb 17 '14 05:02

koss


3 Answers

You might want to look at Apache Digester as well : http://commons.apache.org/proper/commons-digester/guide/core.html - this doesn't use a template-approach , but it looks quite well suited for the problem stated here.

( Originally a comment: but OP stated that this provided a viable solution for them - so moving to answer )

like image 181
monojohnny Avatar answered Sep 28 '22 17:09

monojohnny


Another good XML serializer / deserializer is Simple:

File source = new File("person.xml");
Person person = serializer.read(Person.class, source);
like image 20
Pär Svanström Avatar answered Sep 28 '22 18:09

Pär Svanström


Are you sure you need templates? Maybe just serialization from XML to Object is enough for you, then you can try XStream http://x-stream.github.io/tutorial.html

like image 40
Anton Eremenko Avatar answered Sep 28 '22 17:09

Anton Eremenko