如何将xml文件内容映射到Java对象 [英] How to map xml file content to Java object

查看:220
本文介绍了如何将xml文件内容映射到Java对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发项目,需要将xml文件映射到基于Java的对象。



我googled发现JAXB是用于映射XML-Java的标准库并回到XML。



我正在处理部署XML格式的许多数据源文件的应用程序。而且我想在运行时从这个XML文件中找出某些属性。下面给出了一个这样的XML文件的例子:

 <?xml version =1.0encoding =UTF-8 ?> 
< datasources xmlns =http://www.jboss.org/ironjacamar/schemaxmlns:xsi =http://www.w3.org/2001/XMLSchema-instance
xsi :schemaLocation =http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd\">
< datasource jndi-name =java:jboss / datasources / FDMS_DemoDSpool-name =FDMS_DemoDS>
< connection-url> jdbc:mysql:// localhost:3306 / demo?zeroDateTimeBehavior = convertToNull< / connection-url>
< driver> com.mysql< / driver>
< pool>
< max-pool-size> 60< / max-pool-size>
< / pool>
< security>
< user-name> fduser< / user-name>
< password> fdms!< / password>
< / security>
< / datasource>
< / datasources>

现在我要获取 max-pool-size connection-url 从上面的XML文件使用Java。我尝试使用JAXB,但不幸的是我面临一些问题。



任何人都可以帮助我将这些XML映射到Java对象?

解决方案

最简单的方法是下载 XSD 文件,并使用 xjc 为您生成java类。


  1. 下载 http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd

  2. 启动code> xjc datasources_1_0.xsd

有关 xjc 的更多信息, 绑定编译器 这里


I am working on project where there is need to map xml files to java based objects.

I googled and found JAXB is standard library used to map XML-Java and back to XML.

I am working on application where there are many datasource files in XML format are deployed. And I want to find out certain properties from this XML file at run time. One such example of XML file is given below:

<?xml version="1.0" encoding="UTF-8"?>
<datasources xmlns="http://www.jboss.org/ironjacamar/schema"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd">
<datasource jndi-name="java:jboss/datasources/FDMS_DemoDS" pool-name="FDMS_DemoDS">
      <connection-url>jdbc:mysql://localhost:3306/demo?zeroDateTimeBehavior=convertToNull</connection-url>
      <driver>com.mysql</driver>
      <pool>
          <max-pool-size>60</max-pool-size>
      </pool>
      <security>
          <user-name>fduser</user-name>
          <password>fdms!</password>
      </security>
  </datasource>
</datasources>

Now I want to fetch max-pool-size and connection-url from above XML file using Java. I tried using JAXB but unfortuantely I am facing some issues.

Can anyone help me in mapping these XML to Java Object ?

解决方案

The simplest way in your case is to download the XSD file and use xjc to generate the java classes for you.

  1. Download http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd
  2. Launch xjc datasources_1_0.xsd

More info about xjc, the Binding Compiler here

这篇关于如何将xml文件内容映射到Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆