如何将XML文件另存为Java中SQL Server输出的.xml?

时间:2018-06-27 07:50:58

标签: javascript java sql-server

我想在Java中运行SQL查询,查询结果在xml中。查询结果如下-

<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Rows>
  <Unique_id>6124</Unique_id>
  <DoorNo>12</DoorNo>
  <StreetNo>1</StreetNo>
  <SiteNo>84904</SiteNo>
</Rows>
<Rows>
  <Unique_id>6125</Unique_id>
  <DoorNo>12</DoorNo>
  <StreetNo>2</StreetNo>
  <SiteNo>84904</SiteNo>
</Rows>
</Root>

现在,我想使用Java将上述xml导出到名为QueryResult.xml的外部文件中。 我尝试使用下面的Java脚本,但是无法保存文件。

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");   
con=DriverManager.getConnection("jdbc:sqlserver://sqldatabase:1009;
databaseName=DatabaseName;user=UserName;password=1234");
PreparedStatement ps=con.prepareStatement(QueryName);  
ResultSet rs=ps.executeQuery();
SQLXML xmlVal1= rs.getSQLXML(1);
String val = xmlVal1.getString();
try (PrintWriter out = new PrintWriter(new File("Output.xml"))) {
    out.println(val);
}

查询名称:

  select Distinct Unique_id, DoorNo, StreetNo, Siteno from Table Name where 
  Unqiue_id IN ( '6124','6125') FOR XML RAW ('Rows'), ROOT ('Root'), ELEMENTS XSINIL;

1 个答案:

答案 0 :(得分:1)

SQLXML xmlVal= rs.getSQLXML(1);
String val = xmlVal.getString();
try (PrintWriter out = new PrintWriter("out.xml")) {
    out.println(val);
}

Here is the Oracle Tutorial with code examples

关于您的代码, 1.您忘记对结果集进行next(); 2.您根本不需要SQLXML。

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");   
con=DriverManager.getConnection("jdbc:sqlserver://sqldatabase:1009;
databaseName=DatabaseName;user=UserName;password=1234");
PreparedStatement ps=con.prepareStatement(QueryName);  
ResultSet rs=ps.executeQuery();
rs.next();
String val = rs.getString(1);
try (PrintWriter out = new PrintWriter(new File("Output.xml"))) {
    out.println(val);
}