General Program for converting relational databases into XML files

Source: Internet
Author: User
General purpose of converting a relational database into an XML fileProgram

Always copy from others on the network Source code Today, I also posted my source code today. I believe this program will help you frequently extract data from the database and convert it into an XML file in your daily work.
Recently, one thing in the company's project is to read data from the database table and convert it into an XML file for the client to download. Because there are too many tables in the database, it is impossible to write a conversion program for each table separately. Therefore, after analysis, a general program is written to convert the resultset object into an XML file. In this way, you only need to pass in the path of the query result set (resultset object) and the XML file to be generated, then, assign the property name and element name, correspond to the fields in the corresponding query result set, and call the designover () function to generate the expected XML file. Finally, a sample program is provided.
I am using Dom parsing and written in pure Java. The program includes five classes: createxmlfile. Java, disposal. Java, saveattrname. Java, saveelename. Java, and writexmlfile. java.
Only createxmlfile. Java can really interact with users. If you do not want to understand the program logic, you do not need to worry about other classes. Code Examples:

 

File createxmlfile. Java content:
Package currencycreatexml;

Import java. SQL .*;

Public class createxmlfile
{
Private resultset RS; // you can see from the program below that this field can be omitted, so you are too lazy to change it.
Private string URL; // this field can be omitted from the following program.
Private disposal; // custom class used to collect and process data
Private string root; // name of the root element of the XML file
Private string rootchild; // name of the child node of the Root Node
/**
* @ Param RS: query result set required to create an XML file
* @ Param URL: Specify the path for generating the XML file (including the file name of the XML file)
*/
Public createxmlfile (resultset RS, string URL)
{
This. rs = RS;
This. url = URL;
Disposal = new disposal ();
Disposal. setresultset (this. RS, this. url );
}
// Set the root element name of the XML file
Public void setrootelementname (string root, string rootchild)
{
This. Root = root;
This. rootchild = rootchild;
Disposal. setrootname (this. Root, this. rootchild );
}
// Set the attribute name and index location, starting from 1
/**
* @ Param namestring specifies the attribute name.
* @ Param index specifies the number of fields in the query result set where the attribute value starts from 1)
*/
Public void setattributename (string namestring, int index)
{
Disposal. collectdata (namestring, index, "attribute ");
}
// Set the element name and index position, starting from 1
/**
* @ Param namestring specifies the name of the element.
* @ Param index specifies the number of fields in the query result set where the element value starts from 1)
*/
Public void setelementname (string namestring, int index)
{
Disposal. collectdata (namestring, index, "element ");
}
/**
* Call this rule to create an XML file immediately. Call this method after the attributes and elements have been assigned.
*/
Public void designover ()
{
Disposal. startwrite ();
}
}

File disposal. Java content:

Package currencycreatexml;

Import java. util .*;
Import java. SQL .*;

Class disposal
{
Private resultset RS;
Private string URL;
Private arraylist attrilist = new arraylist (); // a collection class used to store attribute names and field indexes.
Private arraylist elelist = new arraylist (); // a collection class used to store element names and field indexes.
Private string root;
Private string rootchild;
Public void setresultset (resultset RS, string URL)
{
This. rs = RS;
This. url = URL;
}
Public void setrootname (string root, string rootchild)
{
This. Root = root;
This. rootchild = rootchild;
}
@ Suppresswarnings ("unchecked ")
Public void collectdata (string namestring, int index, string type)
{
If (type. Equals ("attribute "))
Attrilist. Add (New saveattrname (namestring, index ));
Else
Elist. Add (New saveelename (namestring, index ));
// System. Out. println ("else ");
// System. Exit (0 );
}
Public void startwrite ()
{
New writexmlfile (attrilist, elelist, RS, URL). Create (root, rootchild );
}
}

File saveattrname. Java content:

Package currencycreatexml;

Class saveattrname
{
Private string attributename;
Private int index;
Public saveattrname (string attributename, int index)
{
This. attributename = attributename;
This. Index = index;
}
Public String getattributename ()
{
Return attributename;
}
Public int getindex ()
{
Return Index;
}
}

Content of the saveelename. Java file:

Package currencycreatexml;

Class saveelename
{
Private string elementname;
Private int index;
Public saveelename (string elementname, int index)
{
This. elementname = elementname;
This. Index = index;
}
Public String getelementname ()
{
Return elementname;
}
Public int getindex ()
{
Return Index;
}
}

File writexmlfile. Java content:

Package currencycreatexml;

Import java. Io .*;
Import java. SQL .*;
Import java. util. arraylist;
Import java. util. iterator;
Import javax. xml. parsers .*;

Import org. W3C. Dom. *; // use Dom to parse
Import org. Apache. Crimson. Tree. *; // jar package used to write XML files

Class writexmlfile
{
Private resultset RS;
Private string URL;
Private arraylist attrilist;
Private arraylist elelist;
Public writexmlfile (arraylist attrilist, arraylist elelist, resultset RS, string URL)
{
This. attrilist = attrilist;
This. elelist = elelist;
This. rs = RS;
This. url = URL;
}
/**
* @ Param root: name of the root element of the XML file
*/
Public void create (string root, string rootchild)
{
Documentbuilderfactory DBF = documentbuilderfactory. newinstance ();
Document Doc = NULL;
Try
{
Documentbuilder DB = DBF. newdocumentbuilder ();
Doc = dB. newdocument ();
}
Catch (parserconfigurationexception E)
{
E. printstacktrace ();
}
Element rootelement = Doc. createelement (Root );
Doc. appendchild (rootelement );
Iterator attri = attrilist. iterator ();
Iterator ele = elelist. iterator ();
// System. Out. println ("iterator ");
Try
{
While (Rs. Next ())
{
Element rootchildelement = Doc. createelement (rootchild );
// System. Out. println ("while ");
While (attri. hasnext ())
{
/**
* Loop to the attribute set to get the element name, then retrieve data from the query result set, and create the element attribute
*/
Saveattrname temp = (saveattrname) attri. Next ();
Rootchildelement. setattribute (temp. getattributename (), RS. getstring (temp. getindex (). Trim ());
}
Rootelement. appendchild (rootchildelement );
While (Ele. hasnext ())
{
/**
* Go To The element set to get the element name, then retrieve data from the query result set, and create a node
*/
Saveelename temp = (saveelename) ELE. Next ();
Element tempelement = Doc. createelement (temp. getelementname ());
Text temptextelement = Doc. createtextnode (Rs. getstring (temp. getindex (). Trim ());
Tempelement. appendchild (temptextelement );
Rootchildelement. appendchild (tempelement );
}
Attri = attrilist. iterator (); // repeats the loop to the set value, the same below
Ele = elelist. iterator ();
}
}
Catch (exception E)
{
E. printstacktrace ();
}
Writexml (DOC );
}
Private void writexml (document DOC)
{
Try
{
Fileoutputstream outstream = new fileoutputstream (URL );
Outputstreamwriter outwriter = new outputstreamwriter (outstream );
(Xmldocument) Doc). Write (outwriter, "gb2312 ");
Outwriter. Close ();
Outstream. Close ();
System. Out. Print ("\ nwrite xmlfile successful! \ N ");
}
Catch (exception E)
{
E. printstacktrace ();
}
}
}

Explanation:
Assume that there is a table named "ccnustudents" in the database ",
The table contains several records, which are converted to an XML file. The conversion rule is to use the record keywords as element attributes, and the others as nodes. Of course, you can also set any fields in the database as attributes or elements based on your own rules. The names of all elements and attributes can be customized. The table content is:

Student ID name: Home Address of the School Department
20033274 Department of Information Management, Huazhong Normal University, gongchang town, Jianli County, Hubei Province, China
20043225 Department of Economics, Central South University for Nationalities, Zhou laozui town, Jianli County, Hubei Province

If the keyword field is "student ID", you can convert the table into an XML file:
The sample code is as follows:
Content of the test function in the test. Java file:

Public static void main (string [] ARGs) throws exception
{< br> sqlexecute conn = new sqlexecute ();
resultset rs = Conn. sqlquery ("select * From ccnustudents");
createxmlfile create = new createxmlfile (RS, "demo. XML ");
create. setrootelementname ("basic student information", "student");
create. setattributename ("student ID", 1);
create. setelementname ("Student name", 2);
create. setelementname ("school", 3);
create. set Elementname ("system", 4);
create. setelementname ("Address", 5);
create. designover ();
}< br> the setattributename (string, INT) function and the string in setelementname (string, INT) function are used to specify the element name or attribute name, the Int-type number is used to associate the value of this element or attribute from the first field in the table. After the program runs the result, an XML file named "demo. xml" is generated in the current directory. The file content is:

<? XML version = "1.0" encoding = "gb2312"?>

<Basic student information>

<Students student ID = "20033274">
<Student Name> Xie </Student name>
<School> Huazhong Normal University </school>
<Department> information management </Department>
<Address> gongchang town, Jianli County, Hubei Province </address>
</Student>

<Students student ID = "20043225">
<Student Name> Avi </Student name>
<School> Central South University for Nationalities </school>
<Department> Economics </Department>
<Address> zhoulaozui town, Jianli County, Hubei Province </address>
</Student>

</Basic student information>

Of course, if the data table contains multiple keywords, you can also specify multiple attributes in the program.
So far, an XML file is generated. Of course, for ease of application, the namespaces and CDATA in XML files are not processed. It is expected to play a leading role.
For program procedures and logic, see the annotations in the class ~.
(-Xiao Xie (QQ: 156411203, please contact us)-2006.7.21 ).
Finally, you do not need to assign the corresponding element or attribute name to each field in the query result set. Instead, you only need, you can assign names to the fields you want to store in the XML file. Finally, do not forget to call the designover () function and tell the program that the assignment has been completed! Pai_^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.