开发者

Suggesstion needed for persisting java objects to xml

开发者 https://www.devze.com 2023-01-26 21:54 出处:网络
We are using hibernate to load data from oracle database. I need to load the data from one of the tables and then store sele开发者_Python百科cted data from this table as an xml file in another table.

We are using hibernate to load data from oracle database. I need to load the data from one of the tables and then store sele开发者_Python百科cted data from this table as an xml file in another table. It would be great if someone could suggest, what would be the best way to achieve this functionality?


Take a look at this question which discusses libraries (such as JAXB and XStream) you can use to convert Java objects to XML.

What is the best way to convert a java object to xml with open source apis


Use Xstream of ThougthWorks.

"XStream is a simple library to serialize objects to XML and back again."


XMLEncoder (java.beans.XMLEncoder) is already included in the JDK and enables you to persist java objects to XML without any external libraries or tools.

An example class:

public class Foo {
   private String foo ;

   public void setFoo(String s) {
     foo = s;
   }

   public String getFoo() {
     return foo;
   }
}

Helper class to serialize to XML:

import java.beans.XMLEncoder;
import java.io.*;

public class FooHelper {
    public static void write(Foo f, String filename) throws Exception{
        XMLEncoder encoder =
           new XMLEncoder(
              new BufferedOutputStream(
                new FileOutputStream(filename)));
        encoder.writeObject(f);
        encoder.close();
    }
}

The resulting XML:

<?xml version="1.0" encoding="UTF-8"?> 
<java version="1.5.0-beta" class="java.beans.XMLDecoder"> 
 <object class="Foo"> 
  <void property="foo"> 
   <string>bar</string> 
  </void> 
 </object> 
</java>


If you are using JPA to persist your entities then look at if you can switch your provider to EclipseLink. If can convert the the same JPA persistent pojos to XML for you. So you will only have to deal with single library.


You can take a look at xmlbeans

0

精彩评论

暂无评论...
验证码 换一张
取 消