How to map xml file content to Java object

爱⌒轻易说出口 提交于 2019-12-24 03:04:27

问题


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 ?


回答1:


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




回答2:


If all you want to do is read the xml files in Java, there are lot more options. I personally prefer common digester. Its simple and easy to use.

https://commons.apache.org/proper/commons-digester/

Personally, I feel JAXB is a bit of overkill if all you need to do is read the file . Please note that digester cannot write the xml files back. Dont use it if you need to write back XML's.




回答3:


xpath/jxpath is the most performant option for your case.



来源:https://stackoverflow.com/questions/37920624/how-to-map-xml-file-content-to-java-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!