Java to convert table data into XML and vice versa. Example using MySql

In this tutorial, let us see how to convert MySQL database table data into XML and vice versa. Let us create XML from a table (product) which has two fields named ProductId, ProductName. In this example, the generated XML will contain the table data including Table Name and Structure.

The sample XML to be created is given below.

For retriving Table Name and Table Structure, we will use getMetaData() of ResultSetMetaData.

The complete java program is given below for converting Table dats to XML and vice versa.
It has two methods.
generateXML()– converts table data to XML. The XML includes table data and structure of the table. Table structure includes basic details like table name, column name, column type and column precision. You can include more details as per your requirement.

xmlToTable() – converts XML into table data. DDL and DML is generated by parsing the XML to create table structure and insert table data.

 

 

For Running the program, create a table product with the fields productId and productName

DDL to create the table

CREATE TABLE product (productId varchar(10),productName varchar(100));

Insert two records

insert into product values(‘I1′,’LCD TV’);
insert into product values(‘I1′,’LED TV’);

 

Running the above program, will create the following

1. XML File

2. copy of product table with data named product1

table to xml and viceversa

 

You may also like

Leave a Reply