I would like to convert data from a table to an XML file. The data is in the following format
Continent Country County Town
--------------------------------------------------------------
Africa Kenya South Mombasa
Africa Egypt South Cairo
Europe England North Birmingham
Asia Japan South Tokyo
The resultant XML document that will be produced is similar to the one shown below:
<continents>
<continent name="Africa">
<countries>
<country>
<countryName>Kenya</countryName>
<county>South</county>
<town>Mombasa</town>
</country>
<country>
<countryName>Egypt</countryName>
<county>South</county>
<town>Cairo</town>
</country>
</countries>
</continent>
<continent name="Europe">
<countries>
<country>
<countryName>England</countryName>
<county>North</county>
<town>Birminghan</town>
</country>
</countries>
</continent>
<continent name="Asia">
<countries>
<country>
<countryName>Japan</countryName>
<county>South</county>
<town>Tokyo</town>
</country>
</countries>
</continent>
</continents>
What i am planning to do is read the data from the database into a JPA object. This returns a list of the following object
@Entity
@Indexed
@Table(name="TOWN")
public class Town {
protected String continent;
protected String country;
protected String county;
protected String town;
@Id
@Column(name="CONTINENT")
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
@Column(name="COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
@Column(name="COUNTY")
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
@Column(name="TOWN")
public String getTown() {
return town;
}
public void setTown(String town) {
this.town = town;
}
}
When i run the call to retrieve the rows from the database, i will get the list in the following format:
List<Town> towns = entityManager.getAllTowns();
To be able to generate the XML file, i have to iterate the list and process each of the "Town" object. I can use DOM but i feel that there will be lots of for loops and if statements to be able to generate the XML document. Is it possible to generate the XML document without having to iterate through the list to build the xml file shown above?
I have converted a JPA object to Jaxb but this was a flat relationship with a one to one mapping (i.e. no child or inner elements in the XML structure). I dont understand how to do the child elements and the conditional rules that would be required for the sample xml file.
I am using JPA/Hibernate with Spring 3. Is it possible to generate the sample xml file or do i need to do it manually (Using for loops and if statements) because of the format of the XML file?
Thanks