简体   繁体   English

从数据库创建XML文件?

[英]Creating XML file from Database?

I have a database and there are multiple tables in db. 我有一个数据库,db中有多个表。 Now I want to generate the XML file of a particular table or all the tables at on shot. 现在,我想生成特定表或所有表的XML文件。 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: 现在,我想生成以下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>   

Note: I need to add the tags like < XYZ > and < Users > from my side. 注意:我需要从我的侧面添加诸如<XYZ>和<Users>之类的标签。

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. 如果表很大,则首先创建XML文档的成本很高。 It would be better to loop through the SQL result set and for every record write an XML "record." 最好遍历SQL结果集,并为每条记录编写一个XML“记录”。

Then the XML tags you chose, are the same as the field names. 然后,您选择的XML标记与字段名称相同。 You could also opt for the following, which makes it possible to validate the XML by some schema/DTD. 您还可以选择以下内容,这使得可以通过某些模式/ DTD验证XML。

Bangalore SIP IP 班加罗尔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. 要转储表,可以使用SELECT * FROM table ,但是您也可以从连接中查询DatabaseMetaData:所有表,列等。 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. 对于您的方法,错误是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>");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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