A general program for transforming relational database into XML file

Source: Internet
Author: User
Tags add object key sql query return string trim
xml| Program | data | The database is always on the network copy other people's source code, today I also posted their own today's source, I believe that this program will be in peacetime work in the ordinary need to extract data from the database into an XML file will help.
One of the most recent company projects is to read data from a database table and then convert it to an XML file for download by the client, because there are too many tables in the database to write a translator for each individual table. Then, after analysis, wrote a common program to convert the ResultSet object into an XML file. In this way, you can generate the desired XML file by simply passing the query result set (ResultSet object) and the path of the XML file to be generated, and then assigning the property name, the element name, and the field in the corresponding query result set, and finally calling the Designover () function. Finally, a sample program is given.
I was parsed using DOM, written in a pure Java language, and the program consists of 5 classes: Createxmlfile.java, Disposal.java, Saveattrname.java, Saveelename.java, Writexmlfile.java
The real interaction with the user is only Createxmlfile.java, if you do not want to understand the program logic, you can not control other classes. Code explanations and examples are as follows:

File Createxmlfile.java content:
Package currencycreatexml;

Import java.sql.*;


public class Createxmlfile
{
Private ResultSet RS; From the following program can be seen, this field can be omitted, too lazy to change, hehe
Private String URL; From the following program can be seen, this field can be omitted, too lazy to change, hehe
private disposal disposal; A custom class to collect and process data
private String root; The root element name of the XML file
Private String Rootchild; The element name of the child node of the root node
/**
* @param rs: Query result set required to create an XML file
* @param URL: Specifies the generation path of 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);
}
To set the root element name of an XML file
public void Setrootelementname (String root,string rootchild)
{
This.root=root;
This.rootchild=rootchild;
Disposal.setrootname (This.root,this.rootchild);
}
Sets the name and index position of the property, starting at 1
/**
* @param namestring The name of the specified property
* @param index Specifies the value of this property in the first few fields in the query result set (the field is indexed from 1)
*/
public void Setattributename (String namestring,int index)
{
Disposal.collectdata (namestring,index, "attribute");
}
Sets the name and index position of the element, starting at 1
/**
* @param namestring The name of the specified element
* @param index Specifies the value of this element in the first few fields in the query result set (the field starts at 1)
*/
public void Setelementname (String namestring,int index)
{
Disposal.collectdata (Namestring,index, "element");
}
/**
* Call this method to begin creating an XML file immediately, calling this method after both the property and the element 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 (); Collection class for storing property names and field indexes
Private ArrayList elelist=new ArrayList (); Collection class used to store the element name and field index
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
Elelist.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;
}
}

File Saveelename.java content:

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.*; Using DOM parsing
Import org.apache.crimson.tree.*; The jar package that you need to write an XML file

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 the root element name of the Root: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 collection to take the element name, then obtain the data from the query result set, and create the element attributes
*/
Saveattrname temp= (Saveattrname) attri.next ();
Rootchildelement.setattribute (Temp.getattributename (), Rs.getstring (Temp.getindex ()). Trim ());
}
Rootelement.appendchild (rootchildelement);
while (Ele.hasnext ())
{
/**
* Loop to the element collection to take the element name, then get the data from the query result set, and create the 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 (); Repeat loops to the collection for values, 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 ();
}
}
}

Explain:
Suppose there is a table in the database named "Ccnustudents",
There are several records in the table, which are now converted to XML files, and the rules I convert are the attributes of the element to the key of the record, others as the end point. Of course, you can also set any field in the database to a property or element in your own rules. The names of all elements and attributes can be customized, and the contents of the table are:

Name of school No home address
20033274 Evil Huazhong Normal University information management Department Jianli County Gong Chang Zhen, Hubei Province
20043225 The economic Department of the Zhongnan University of Nationalities, Jianli County, Hubei Province, Zhou Lao Ju Zhen

If the key field is "school number," You can convert the table to an XML file:
The sample code is as follows:
The contents of the test function in file Test.java:

 public static void main (String[] args)  throws exception
 {
  sqlexecute conn=new sqlexecute ();
  resultset rs=conn.sqlquery ("select * from ccnustudents");
  createxmlfile create = new createxmlfile (RS, "demo.xml");
  create.setrootelementname ("Student basic Information", "student");
  create.setattributename ("Student number", 1);
  create.setelementname ("Student's name", 2);
  create.setelementname ("School", 3);
  create.setelementname ("in the department", 4);
                   create.setelementname ("Address", 5);
  create.designover ();
 } A String in the
function Setattributename (string,int) and Setelementname (String,int) is used to specify either an element name or a property name. The value of an int number to associate this element or attribute is taken from the first few fields in the table. After the program runs the results, an XML file named "Demo.xml" is generated in the current directory, with the contents:

<?xml version= "1.0" encoding= "GB2312"?>

< student basic information >

< student student Number = "20033274" >
< student's name > Evil </Student's name >
< school > Huazhong Normal University </school >
< department > Information Management </Department >
< address > </, Jianli County Gong Chang Zhen, Hubei province >
</Students >

< student student Number = "20043225" >
< Student's name > </Student's name >
< school > </University of South-central nationalities >
< Department > Economics Department </Department >
< address > </address, Jianli County town, Hubei province >
</Students >

</Students basic Information >

Of course, if you have more than one keyword in your datasheet, you can also specify multiple properties in your program.
Thus, an XML file is generated. Of course, for the sake of simplicity, the namespaces and CDATA in the XML file are not processed. Hope can play a role in the.
Program flow and logic can refer to the comments in the class.
(-Small Evil (qq:156411203, welcome Exchange)-2006.7.21).
Finally, add a point you don't need to assign an element or attribute name to the fields in each query result set, but simply assign names to those fields that you want to store in the XML file, and finally, don't forget to call the Designover () function, Tell the program that the assignment is complete! '

Note: This paper has been transferred from Http://bbs.xml.org.cn/dispbbs.asp?boardID=17&replyID=75002&ID=41933&skin=1




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.