从数据库创建XML文件?

时间:2016-08-03 09:57:55

标签: java xml java-ee xml-parsing

我有一个数据库,db中有多个表。现在我想生成特定表的XML文件或正在运行的所有表。 我在网上尝试了很多东西,但不能做我想做的事情。 假设我有一个像这样的表:

 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

现在我想生成以下XML文件:

 <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>   

注意:我需要添加像&lt;这样的标签。 XYZ&gt;和&lt;用户&gt;在我身边。

我试图做下面的事情:

   @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;

}

请提供任何其他方法,以便在从DB检索数据后,我可以从我这边添加根标签。 在此先感谢.......

2 个答案:

答案 0 :(得分:0)

为什么不简单地创建一个包含模板行的字符串并用您的值替换占位符?

!! 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>";

答案 1 :(得分:0)

有几种选择。如果表很大,首先创建XML文档的成本很高。最好循环访问SQL结果集,并为每条记录写一个XML&#34;记录。&#34;

然后,您选择的XML标记与字段名称相同。 您还可以选择以下内容,这样就可以通过某种模式/ DTD验证XML。

     班加罗尔      啜      IP

可以转储表SELECT * FROM table,但您也可以从连接中查询DatabaseMetaData:所有表,列等。如果事先不知道表名,您可以选择。

使用您的方法,错误是ResultSet的范围有点像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>");
}