简体   繁体   中英

Creating XML file from Database?

I have a database and there are multiple tables in db. Now I want to generate the XML file of a particular table or all the tables at on shot. I tried lots of stuff available on net, but not able to do what i was trying. Suppose I have a table like:

 id    created  end_num    gateway   type   modified  name    start_num  sub_type
 1       NULL    30      172.20.1.2   SIP     NULL   Bangalore    20       IP   

 2       NULL    15      172.20.2.5   SIP     NULL   Delhi        15       UDP

Now I want to generate of following XML File:

 <XYZ>
   <users>
     <user name="Bangalore" type="SIP">
     <sub_type>IP</sub_type>
     <start_num>20</start_num>
     <end_num>30</end_num>
     <gateway>172.20.1.2</gateway>
     </user>

     <user name="Delhi" type="SIP">
     <sub_type>UDP</sub_type>
     <start_num>15</start_num>
     <end_num>15</end_num>
     <gateway>172.20.2.5</gateway>
     </user>

   </users>
 </XYZ>   

Note: I need to add the tags like < XYZ > and < Users > from my side.

I was trying to do something like below:

   @Transactional(readOnly=true)
   public void getCommit() throws SQLException, ParserConfigurationException 
  {
     System.out.println("INSIDE COMMIT REPO");
     // TODO Auto-generated method stub

     //String query = "FROM trunk";
     SessionImpl sessionImpl = (SessionImpl)sessionFactory.getCurrentSession();
     Connection connection = sessionImpl.connection();
     PreparedStatement preparedStatement = connection.prepareStatement("Select * FROM trunk");
     ResultSet rs = preparedStatement.executeQuery();
     ResultSetMetaData rsmd = rs.getMetaData();
     int columnsNumber = rsmd.getColumnCount();
     while (rs.next()) 
     {
        for (int i = 1; i <= columnsNumber; i++) {
        if (i > 1) System.out.print(",  ");
        String columnValue = rs.getString(i);
        System.out.print(columnValue + "  -----------  " +      rsmd.getColumnName(i));
      }
      System.out.println(" ");
    }
    toDoucumet(rs);
 }

 private Document toDoucumet(ResultSet rs) throws ParserConfigurationException, SQLException {
  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  DocumentBuilder builder = factory.newDocumentBuilder();
  Document doc = builder.newDocument();
  Element results = doc.createElement("Users");
  doc.appendChild(results);
  ResultSetMetaData rsmd = rs.getMetaData(); **// Getting Error at this line  IllegalStateException**
  int colCount  = rsmd.getColumnCount();
  System.out.println(colCount);
  while(rs.next()){
  Element row = doc.createElement("user");
  results.appendChild(row);
  for (int i = 1; i <= colCount; i++) 
  {
    System.out.println(rsmd.getColumnName(i));
    String columnName = rsmd.getColumnName(i);
    Object value = rs.getObject(i);

    Element node = doc.createElement(columnName);
    node.appendChild(doc.createTextNode(value.toString()));
    row.appendChild(node);
   }
}
return doc;

}

Please provide me any other way to do so that after retrieving data from DB I can able to add root tags from my side. Thanks In Advance.......

Why not simply creat a string containing a template row and replace placeholders with your value?

!! PSEUDO CODE !!

String template = "<user name=\"%userName%\" type=\"%userType%\"><sub_type>%subType%</sub_type><start_num>%start%</start_num><end_num>%end%</end_num><gateway>%gateway%</gateway></user>";

string result = "<XYZ><users>";
for (int i = 1; i <= colCount; i++) {
    string user = template.replace("%userName%", valueOfColoumn("name"));
    user = user.replace("%userType%", valueOfColoumn("type"));
    ...
    result += user;
}
result += "</users></XYZ>";

There are a couple of options. First creating an XML document is costly if the table is large. It would be better to loop through the SQL result set and for every record write an XML "record."

Then the XML tags you chose, are the same as the field names. You could also opt for the following, which makes it possible to validate the XML by some schema/DTD.

Bangalore SIP IP

To dump a table SELECT * FROM table is possible, but also you can query the DatabaseMetaData from the connection: all tables, columns, and so on. You might choose that when the table names are not known in advance.

With your approach, the error was that the ResultSet is scoped, a bit like the Iterator.

try (PrintWriter xmlOut = ...) {
    xmlOut.println("<?xml version="1.1"?>");
    xmlOut.println("<db>");

    String tableName = "trunk";
    try (PreparedStatement preparedStatement = connection.prepareStatement("Select * FROM " + tableName);
             ResultSet rs = preparedStatement.executeQuery()) {
         ResultSetMetaData rsmd = rs.getMetaData();
         int columnsNumber = rsmd.getColumnCount();

         xmlOut.printf("    <%s>%n", tableName);
         while (rs.next()) {
             for (int i = 1; i <= columnsNumber; i++) {
                 String columnName = rsmd.getColumnLabel(i); // Or Name
                 String columnValue = rs.getString(i); // Check the type
                 xmlOut.printf("        <%s>%s</%s>%n",
                     columnLabel, columnValue, columnLabel);
             }
         }
         xmlOut.printf("    </%s>%n", tableName);
    } // Closes statement and result sets.
    xmlOut.println("</db>");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM