Serializing Java Bean to XML

I would like to know if it is possible with XMLBeans to convert existing java beans to XML.
I learnt by going trhu' few materials of XMLBeans that we need to create bean classes from XSD and can use these classes for marshalling/unmarshalling.
But I have java beans already defined which I want to serialize/deserialize to/from XML.
Thanks in advance.
--Ramu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

If you are not interested in writing a bunch of code (which is probably the case), I know of a couple options for WLS 8.1:
1. Use the "undocumented" and "unsupported" java2xsd class, in the %WL_HOME%\server\lib\webservices.jar.
2. Use the Java2Schema tool in the Systinet Server for Java product.
Here's the contents of a sample build.xml that uses the java2xsd class:
<project
name="java2xsd"
default="assemble"
basedir="."
>
     <path id="compile.classpath">
          <fileset dir="d:/bea81sp4/">
               <include name="lib/tools.jar" />
          </fileset>
          <fileset dir="d:/bea81sp4/weblogic81">
               <include name="server/lib/weblogic.jar"/>
               <include name="server/lib/webservices.jar"/>
          </fileset>
     </path>
     <target name="clean">
          <delete dir="xsd" />
     </target>
     <target name="run-java2xsd">
<delete dir="xsd" />
<mkdir dir="xsd"/>
<java
     classname="weblogic.xml.schema.binding.util.java2xsd"
fork="true"
>
<jvmarg line="-Djava.io.tmpdir=xsd"/>
<arg line="
com.acme.world.schema.x2005.x11.elending.Loan
com.acme.world.schema.x2005.x11.elending.Applicant
com.acme.world.schema.x2005.x11.ebillpay.Account
"/>
<classpath>
<path refid="compile.classpath"/>
<pathelement location="classes"/>
</classpath>
</java>
     </target>
     <target name="assemble" depends="run-java2xsd">
     </target>
</project>
Here, you would replace the paths in the <path> element of course, but you would also need to come up with a way to provide a list of the JavaBean classes to process. The good thing is that java2xsd is smart enough to put all the classes in a given Java package, in the same <xs:schema> element :-) For instance, in:
<arg line="
com.acme.world.schema.x2005.x11.elending.Loan
com.acme.world.schema.x2005.x11.elending.Applicant
com.acme.world.schema.x2005.x11.ebillpay.Account
"/>
the complexType element for "Loan" and "Applicant", will be defined in the same <xs:schema>. There will only be one schemas.xsd file. I don't know of an easy way to change the file name, but it will contain a <xs:schema> for each unique Java package name. Once you have this schemas.xsd file, you can decide how you want to create the XMLBeans from it. You can either break each <xs:schema> element out into it's own .xsd file, or create a WSDL that uses the contents of the schemas.xsd file. You'll notice that there is a <type> element wrapping all the <xs:schema> elements in the schemas.xsd file, which is exactly the name of the element that WSDL uses :-)
Again, java2xsd is not a "supported" class, so don't confuse it (or the information provided above) with being "the tool that BEA provides" for doing what you want to do :-)
Regards,
Mike Wooten

Similar Messages

  • Serializing a Bean to XML

    Serializing a Bean to XML .
    when it is done ?

        // Create an object and set properties
        MyClass o = new MyClass();
        o.setProp(1);
        o.setProps(new int[]{1, 2, 3});
        try {
            // Serialize object into XML
            XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
                new FileOutputStream("outfilename.xml")));
            encoder.writeObject(o);
            encoder.close();
        } catch (FileNotFoundException e) {
        // This class defines two properties - prop and props
        public class MyClass {
            // The prop property
            int i;
            public int getProp() {
                return i;
            public void setProp(int i) {
                this.i = i;
            // The props property
            int[] iarray = new int[0];
            public int[] getProps() {
                return iarray;
            public void setProps(int[] iarray) {
                this.iarray = iarray;
        }and here is the XML created
    <?xml version="1.0" encoding="UTF-8"?>
        <java version="1.4.0" class="java.beans.XMLDecoder">
            <object class="MyClass">
                <void property="prop">
                    <int>1</int>
                </void>
                <void property="props">
                    <array class="int" length="3">
                        <void index="0">
                            <int>1</int>
                        </void>
                        <void index="1">
                            <int>2</int>
                        </void>
                        <void index="2">
                            <int>3</int>
                        </void>
                    </array>
                </void>
            </object>
        </java>My Question is when we Serializing a Bean to XML ? why do we do it ? what is the advantage of doing it ?
    have you used it ? please tell why did you choose this to use ?

  • Transform Java Beans into XML documents?

    Hi,
    I have standard Java Beans (which are not generated out of XML documents), can I transform them into
    XML documents even if they are not generated out of XML documents originally?
    If not, is there any toll which can do that?
    regards,

    Looks like the java.beans.XMLEncoder class is where you should start.

  • Serializing Java Objects to XML files

    Hi,
    We looking for SAP library which can serialize Java Objects into XML files.
    Can you point us were to find it ?
    We have found such open source library called "XStream" at the following link
    http://www.xml.com/pub/a/2004/08/18/xstream.html
    Is it allowed to use that library inside SAP released software ?
    Thanks
    Orit

    How about https://www.sdn.sap.com/irj/sdn/go/portal/prtroot/docs/webcontent/uuid/83f6d2fb-0c01-0010-a2ba-a2ec94ba08f4 [original link is broken] [original link is broken]? Depends on your use cases...
    Both are supported in SAP NW CE 7.1.
    HTH!
    -- Vladimir

  • Creating a serialized java bean

    I want to store a hashcode in a serialized bean... This hashcode shld be accessible by other jsps, servlets. How is the .ser file created ?

    http://java.sun.com/docs/books/tutorial/essential/io/serializing.html

  • Convert Serialized Java Objects to XML

    I have seen numerous ways that you can modify a java application to serlialize it's data as XML rather than a binary stream. Does anyone know if there are any utilities, libraries, DLLS, tools, whatever to convert an already serialized binary stream to an XML file.
    At the moment I am working on a script to do this, and it works for simple objects, but I am hitting snags as I test with more complicated class heirachies. I would love to find something that already does this for me.

    I want to read data serialized by a java program in a C++ application. I don't want to have to modify the java application, but I do want to make it's data available in other applications.
    I could modify the java app and serialize it's data in XML, but that isn't the prefered solution. :)

  • JAVA BEANS to XML

    how to convert JAVABEAN to XML Data.
    which is the best method for this.
    Please help

    ASHA.MK wrote:
    how to convert JAVABEAN to XML Data.XMLBeans is good from what i hear, but there are others out there.
    which is the best method for this.there is no best method for doing anything
    Please helphelp yourself by doing your own research on the web next time

  • Philisophical Question:  Tools for synchronizing JSPs, Java Beans and XML?

    This is a "best practices" question...
    The JSTL and JSF tags provide a lot of support for minimizing the amount of text that must be included in a JSP page. For example:
    <c:out value="${customer.firstName}"/>This snippet will find an object named "customer" in any of the JSP scopes, extract the value of the property named "firstName", and output it as part of the page.
    Here are my questions:
    (1) Is there a recommended method to communicate to the page designer what objects are in scope for a particular page, and what the properties of those objects are?
    (2) Is there any programmatic way to determine from the program's source code that an object with the specified name and of the expected type will be in scope at run time?
    I would love to have an IDE that would be able to help the page designer by providing a list of the objects that are expected to be in scope, along with the name of their properties. What conventions exist to make this possible?

    Maybe you like this, it's one of dozens of tools for Struts and in version 3.0
    http://www.scioworks.com/scioworks_camino.html
    hth,
    .V

  • How to generate .java file from xml?

    Does anyone have an idea of how i can generate .java file from xml file? Tools like jakrata digester, JOX are there but both of them are useful in populating java beans from xml. My requirement is to generate .java file from .xml with getters and setters methods for xml elements/attributes. I also tried JAXB. But JAXB generates bunch of files and most of them are interfaces, which is not going to work for me.
    For e.g. i have following xml file and i want to generate Address.java file with getters/setters. Any ideas?
    <?xml version='1.0' encoding='UTF-8' ?>
    <Address>
    <FirstName type="String"/>
    <PoBox type="int"/>
    </Address>
    Thanks,
    Vicky

    Crosspost.
    http://forum.java.sun.com/thread.jsp?thread=475564&forum=4&message=2205846

  • Creating XML file from Java Bean

    Hi
    Are there any standard methods in Java 1.5 to create XML file from java bean,
    i can use JAXB or castor to do so,
    But i would like to know if there is any thing in java core classes,
    I have seen XMLEncoder, but this is not what i want.
    Any ideas
    Ashish

    Marshall JavaBean to an XML document with JAXB or XMLBeans.

  • Create XML dynamically from schema and Java bean

    Hi,
    I'm looking for suggestions on the best approach to create an XML file programatically from a schema and Java bean.
    The schema used is not fixed and may vary with each request so a dynamic way to create the XML is required.
    Is there an API available that allows me to achieve this easily? Any help would be appreciated to point me in the right direction.
    Thanks.

    XMLBeans or JAXB should work for you.
    - Saish

  • How to get an XML string from a Java Bean without wrting to a file first ?

    I know we can save a Java Bean to an XML file with XMLEncoder and then read it back with XMLDecoder.
    But how can I get an XML string of a Java Bean without writing to a file first ?
    For instance :
    My_Class A_Class = new My_Class("a",1,2,"Z", ...);
    String XML_String_Of_The_Class = an XML representation of A_Class ?
    Of course I can save it to a file with XMLEncoder, and read it in using XMLDecoder, then delete the file, I wonder if it is possible to skip all that and get the XML string directly ?
    Frank

    I think so too, but I am trying to send the object to a servlet as shown below, since I don't know how to send an object to a servlet, I can only turn it into a string and reconstruct it back to an object on the server side after receiving it :
    import java.io.*;
    import java.net.*;
    import java.util.*;
    class Servlet_Message        // Send a message to an HTTP servlet. The protocol is a GET or POST request with a URLEncoded string holding the arguments sent as name=value pairs.
      public static int GET=0;
      public static int POST=1;
      private URL servlet;
      // the URL of the servlet to send messages to
      public Servlet_Message(URL servlet) { this.servlet=servlet; }
      public String sendMessage(Properties args) throws IOException { return sendMessage(args,POST); }
      // Send the request. Return the input stream with the response if the request succeeds.
      // @param args the arguments to send to the servlet
      // @param method GET or POST
      // @exception IOException if error sending request
      // @return the response from the servlet to this message
      public String sendMessage(Properties args,int method) throws IOException
        String Input_Line;
        StringBuffer Result_Buf=new StringBuffer();
        // Set this up any way you want -- POST can be used for all calls, but request headers
        // cannot be set in JDK 1.0.2 so the query string still must be used to pass arguments.
        if (method==GET)
          URL url=new URL(servlet.toExternalForm()+"?"+toEncodedString(args));
          BufferedReader in=new BufferedReader(new InputStreamReader(url.openStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
        else     
          URLConnection conn=servlet.openConnection();
          conn.setDoInput(true);
          conn.setDoOutput(true);           
          conn.setUseCaches(false);
          // Work around a Netscape bug
          conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
          // POST the request data (html form encoded)
          DataOutputStream out=new DataOutputStream(conn.getOutputStream());
          if (args!=null && args.size()>0)
            out.writeBytes(toEncodedString(args));
    //        System.out.println("ServletMessage args: "+args);
    //        System.out.println("ServletMessage toEncString args: "+toEncodedString(args));     
          BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
          while ((Input_Line=in.readLine()) != null) Result_Buf.append(Input_Line+"\n");
          out.flush();
          out.close(); // ESSENTIAL for this to work!          
        return Result_Buf.toString();               // Read the POST response data   
      // Encode the arguments in the property set as a URL-encoded string. Multiple name=value pairs are separated by ampersands.
      // @return the URLEncoded string with name=value pairs
      public String toEncodedString(Properties args)
        StringBuffer sb=new StringBuffer();
        if (args!=null)
          String sep="";
          Enumeration names=args.propertyNames();
          while (names.hasMoreElements())
            String name=(String)names.nextElement();
            try { sb.append(sep+URLEncoder.encode(name,"UTF-8")+"="+URLEncoder.encode(args.getProperty(name),"UTF-8")); }
    //        try { sb.append(sep+URLEncoder.encode(name,"UTF-16")+"="+URLEncoder.encode(args.getProperty(name),"UTF-16")); }
            catch (UnsupportedEncodingException e) { System.out.println(e); }
            sep="&";
        return sb.toString();
    }As shown above the servlet need to encode a string.
    Now my question becomes :
    <1> Is it possible to send an object to a servlet, if so how ? And at the receiving end how to get it back to an object ?
    <2> If it can't be done, how can I be sure to encode the string in the right format to send it over to the servlet ?
    Frank

  • Help required in building up the Java Bean for an XML data

    Hi ,
    I want to build a Java bean which will actually represent an xml data . The class will be named as User and it will typically represent the data in the follwing xml:
    <user>
    <cwsId>barbete</cwsId>
    <firstName>William</firstName>
    <lastName>Barber</lastName>
    <status>true</status>
    <role>
    <roleCode>1000000177</roleCode>
    <roleName>Customer Administrator</roleName>
    </role>
    <language>en</language>
    <country>US</country>
    <preferences>
    <equipmentGroup>2717</equipmentGroup>
    <dateFormat>MON-dd-yyyy</dateFormat>
    <timeFormat>HH:MI AM</timeFormat>
    <timeZone>-12:00</timeZone>
    <daylightSavings>Y</daylightSavings>
    <location>NC</location>
    <recordsPerPage>10</recordsPerPage>
    <historyPeriod>3</historyPeriod>
    <distanceUnit>MILE</distanceUnit>
    <fuelUnit>G</fuelUnit>
    <unitIdDisplay>E</unitIdDisplay>
    <smuUpdate>W</smuUpdate>
    <countries>
    <country>
    <countryCode>GB</countryCode>
    <countryName>UNITED KINGDOM</countryName>
    </country>
    <country>
    <countryCode>US</countryCode>
    <countryName>UNITED STATES</countryName>
    </country></countries>
    </preferences>
    </user>
    Now for single child nodes like cwsId of the main user node i have kept properties like
    private String cwsId;
    But i am not sure as to how to represent the nodes which contain subnodes like "preferences"node. Any ideas?What is the standard practice?

    One thing you could do is create an object model first, which will contain all the data for your user.
    then all you need in the bean is a Hashtable with the name of the user as a key, and the user-object (which is actually the complete object model) as a value.
    with the XML stated by you, you would get an object model something like this:
    Class User
        String cwsid;
        String firstName;
        ArrayList<Role> roles = new ArrayList<Role>(); //I'm assuming a user can have more then one role.
        ArrayList<Country> countries = new ArrayList<Country>();
    class Role {
        String code;
        String name;
    class Country {
        String code;
        String name;
    }And so on for all the varioous elemets of your XML.

  • Java Bean to check for Well-formed  XML DOC?

    Hi All,
    I am new to the Java XML API's. Does anyone have an example of
    a Java Bean that i can pass an XML String and check if the
    XML document is well formed?
    Thanks
    Joe

    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(xmlString)));try/catch this ugly line, if no parse exception and a non -null doc exists then your XML is well-formed.
    of course if your XML contains namespaces, you would have to setup correctly the document builder.

  • Do all JSP/Java bean webapps need an xml file?

    Hi all,
    I have a jsp/ java bean webb application. This is being run on Resin at
    Lunarpages.
    The site has been shut down due to 'class-loader' not found. I was told it
    was causing problems for other java users on the server.
    I realise this is limited information but any insight would be welcome.
    This is our first JSP / java bean web app.
    Also if anyone could tell me briefly the purpose of an xml document in a JSP/Java bean webapplication I would greatly appreciate it.
    Thanks in advance
    Regards
    Jim

    Hi there,
    Thanks for the reply.
    Our application allows people to purchase wedding pictures online. It ran locally on resin we then had to change all the relative file paths in order to deploy it on lunarpages.
    Lunarpages use resin also.
    We had the application tested and working on Lunarpages for the last week .This morning they sent us a message saying they had shut our JSP pages down as our application was causing problems for other java users. errant code unknown element ' class-loader' .
    Not too much help from lunarpages...
    thanks

Maybe you are looking for