【问题标题】:generate xml using xsd schema and output of a sql query使用 xsd 模式和 sql 查询的输出生成 xml
【发布时间】:2015-09-04 11:48:52
【问题描述】:

我的 Java 应用程序需要基于 XSD 模式生成 XML。生成的 XML 将包含将由 SQL 查询返回的数据。 任何使用的库都应该与 JBoss EAP6 兼容,可能还兼容旧版本。

有人建议使用 Apache Xalan 库,但我找不到好的起点。

有没有人做过类似的事情?

【问题讨论】:

标签: java xml xsd


【解决方案1】:

如果我是你,我会使用 JAXB api 根据 sql 查询的输出创建 xml 输出。 JAXB api 是 J2EE 标准之一,它们是最可能与许多容器兼容的 api。

我没有看到你的代码,但我建议以下解决方案:

您可以使用 ORM 框架或仅使用纯 JDBC。从 DB 获取数据到内存后,您必须将它们保存在一些类似 Bean 的类实例中。

另一方面,您应该为您的 XSD 生成映射类。这通常使用 JAXB 命令行工具或 IDE 工具(在后台使用该命令行工具)来完成。我建议使用 Intellij-Idea 或 Eclipse JAXB 工具。

智能: 例如,如果您有一个 CustomerOrders.xsd 文件,您可以将它放在一个包中,然后通过右键单击它,从 webservices 子菜单中选择“使用 JAXB 从 xml 模式生成 java 代码...”。然后会出现一个对话框来选择输出路径等。您可以在下图中看到:

您使用哪种工具并不重要。最后,他们将为您的 XSD 映射创建一个或多个 java 类。这些类必须存储在您的代码可以在运行时访问的包或文件夹中。然后您唯一的工作就是将您的数据持有者 bean 实例转换为此生成的类的实例。之后,JAXB 会按照您通过 api 的命令将它们编组为 XML 格式的字符串或文件。

使用 JAXB api 的示例代码如下:

try 
{
    CustomerType data = new CustomerType(); // This is a mapping class generated by jaxb tools.
                                            // You should convert your fetched data from DB to this type.
                                            // This object is the root object of your xml output file. 
                                            // Maybe you have some other child level classes under this object
                                            //    which creates your nested tags of your output xml data.
    Marshaller marshaller = JAXBContext.newInstance().createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); // this is for formatting the output xml data
    marshaller.marshal(data, new File("Wherever you want to save!"));
} 
catch (JAXBException e) 
{
    e.printStackTrace();
}

希望这会有所帮助,

祝你好运。

【讨论】:

  • 谢谢 STaefi 我会试一试的!问候
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2011-08-28
  • 2011-04-24
  • 2014-02-22
  • 2012-06-20
  • 2014-07-03
相关资源
最近更新 更多