Mapping XML object to java object gives ClassCastException

Hi All,
I am trying to map a specific XML object to a specific java object using web
services and received the following exception:
java.lang.ClassCastException: weblogic.soap.xml.XMLObject
at $Proxy0.getMonster(Unknown Source)
at serviceClient.TestServiceClient.main(TestServiceClient.java:46)
Exception in thread "main"
I tried to map a simple type:
<types>
<schema targetNamespace='java:biomaterials'
xmlns='http://www.w3.org/1999/XMLSchema'>
<element name="Monster">
<complexType>
<all>
<element name="name"
type="string"/>
<element name="age"
type="int"/>
</all>
</complexType>
</element>
</schema>
</types>
To the following java bean:
package biomaterials;
public class
ster{
private String name;
private Integer age;
public Monster(String name, int age) {
this.name=name;
this.age=new Integer(age);
public String getName() {
return name;
public void setName(String s) {
this.name=s;
public Integer getAge() {
return age;
public void setAge(int n) {
this.age=new Integer(n);
Here is my client code:
package serviceClient;
import java.util.Properties;
import weblogic.soap.codec.CodecFactory;
import weblogic.soap.codec.SoapEncodingCodec;
import weblog
ic.soap.codec.LiteralCodec;
import weblogic.soap.WebServiceProxy;
import weblogic.soap.SoapMethod;
import weblogic.soap.SoapType;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.ejb.*;
import biomaterials.ServiceSession;
import java.io.File;
import java.io.IOException;
import org.w3c.dom.Element;
import biomaterials.Monster;
public class TestServiceClient
public static void main( String[] arg ) throws Exception
Properties h = new Properties();
h.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.soap.http.SoapInitialContextFactory");
h.put("weblogic.soap.wsdl.interface",
ServiceSession.class.getName() );
Context context = new InitialContext(h);
ServiceSession serv =
(ServiceSession)context.lookup("http://localhost:7001/biocat/biomaterials.Se
rviceSession/biomaterials.ServiceSession.wsdl");
//try
//int result = serv.getTheNum();
//String result=serv.getBIXBiologicals();
//int result=serv.setBIXInfo("TARNUMBER");
Monster result=serv.getMonster();
System.out.print("The value is "+result);
} /* end of main */
} /* end of class */
Here is the method in my stateless session bean:
public Monster getMonster()
return new Monster("Sully",3);
And here is my whole wsdl file:
<% response.setHeader( "Content-Type", "text/xml; charset=utf-8" ); %>
<definitions
targetNamespace="java:biomaterials"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="java:biomaterials"
>
<types>
<schema targetNamespace='java:biomaterials'
xmlns='http://www.w3.org/1999/XMLSchema'>
<element name="Monster">
<complexType>
<all>
<element name="name" type="string"/>
<element name="age" type="int"/>
</all>
</complexType>
</element>
</schema>
</types>
<message name="getBIXBiologicalsRequest"></message>
<message name="getBIXBiologicalsResponse">
<part name="return" type="xsd:string" />
</message>
<message name="setBIXInfoRequest">
<part name="arg0" type="xsd:string" />
<part name="arg1" type="xsd:string" />
<part name="arg2" type="xsd:integer" />
</message>
<message name="setBIXInfoResponse"></message>
<message name="getMonsterRequest"></message>
<message name="getMonsterResponse">
<part name="body" element="tns:Monster"/>
</message>
<portType name="ServiceSessionPortType">
<operation name="getBIXBiologicals">
<input message="tns:getBIXBiologicalsRequest"/>
<output message="tns:getBIXBiologicalsResponse"/>
I am using weblogic 6.1 SP1 on WIN NT.
Please help me out in this issue.
Thanks in advance.
Sapan

HI !
i dont think that the servicepack is an issue in this case.
anyway i ahve tried it on 6.1SP4 and still getting similar results.
any pointers will be highly appreciated.
Thanks,
sapan
"manoj cheenath" <[email protected]> wrote in message
news:[email protected]...
I just skimmed through your email. You said you
are using WLS 6.1 SP1. Can you try this using
the latest SP. There are many bug fixes done
after SP1.
Web service support in 6.1 is very limited. But, It
looks like 6.1 can handle the case you are trying out.
regards,
-manoj
"Sapan Agarwal" <[email protected]> wrote in message
news:[email protected]...
Hi All,
I am trying to map a specific XML object to a specific java object usingweb
services and received the following exception:
java.lang.ClassCastException: weblogic.soap.xml.XMLObject
at $Proxy0.getMonster(Unknown Source)
at
serviceClient.TestServiceClient.main(TestServiceClient.java:46)
>>
Exception in thread "main"
I tried to map a simple type:
<types>
<schema targetNamespace='java:biomaterials'
xmlns='http://www.w3.org/1999/XMLSchema'>
<element name="Monster">
<complexType>
<all>
<element name="name"
type="string"/>
<element name="age"
type="int"/>
</all>
</complexType>
</element>
</schema>
</types>
To the following java bean:
package biomaterials;
public class
ster{
private String name;
private Integer age;
public Monster(String name, int age) {
this.name=name;
this.age=new Integer(age);
public String getName() {
return name;
public void setName(String s) {
this.name=s;
public Integer getAge() {
return age;
public void setAge(int n) {
this.age=new Integer(n);
Here is my client code:
package serviceClient;
import java.util.Properties;
import weblogic.soap.codec.CodecFactory;
import weblogic.soap.codec.SoapEncodingCodec;
import weblog
ic.soap.codec.LiteralCodec;
import weblogic.soap.WebServiceProxy;
import weblogic.soap.SoapMethod;
import weblogic.soap.SoapType;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.ejb.*;
import biomaterials.ServiceSession;
import java.io.File;
import java.io.IOException;
import org.w3c.dom.Element;
import biomaterials.Monster;
public class TestServiceClient
public static void main( String[] arg ) throws Exception
Properties h = new Properties();
h.put(Context.INITIAL_CONTEXT_FACTORY,
"weblogic.soap.http.SoapInitialContextFactory");
h.put("weblogic.soap.wsdl.interface",
ServiceSession.class.getName() );
Context context = new InitialContext(h);
ServiceSession serv =
(ServiceSession)context.lookup("http://localhost:7001/biocat/biomaterials.Se
rviceSession/biomaterials.ServiceSession.wsdl");
file://try
file://int result = serv.getTheNum();
file://String result=serv.getBIXBiologicals();
file://int result=serv.setBIXInfo("TARNUMBER");
Monster result=serv.getMonster();
System.out.print("The value is "+result);
} /* end of main */
} /* end of class */
Here is the method in my stateless session bean:
public Monster getMonster()
return new Monster("Sully",3);
And here is my whole wsdl file:
<% response.setHeader( "Content-Type", "text/xml; charset=utf-8" ); %>
<definitions
targetNamespace="java:biomaterials"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="java:biomaterials"
>
<types>
<schema targetNamespace='java:biomaterials'
xmlns='http://www.w3.org/1999/XMLSchema'>
<element name="Monster">
<complexType>
<all>
<element name="name" type="string"/>
<element name="age" type="int"/>
</all>
</complexType>
</element>
</schema>
</types>
<message name="getBIXBiologicalsRequest"></message>
<message name="getBIXBiologicalsResponse">
<part name="return" type="xsd:string" />
</message>
<message name="setBIXInfoRequest">
<part name="arg0" type="xsd:string" />
<part name="arg1" type="xsd:string" />
<part name="arg2" type="xsd:integer" />
</message>
<message name="setBIXInfoResponse"></message>
<message name="getMonsterRequest"></message>
<message name="getMonsterResponse">
<part name="body" element="tns:Monster"/>
</message>
<portType name="ServiceSessionPortType">
<operation name="getBIXBiologicals">
<input message="tns:getBIXBiologicalsRequest"/>
<outputmessage="tns:getBIXBiologicalsResponse"/>
>>
>>
>>
>>
>>
>>
>>
I am using weblogic 6.1 SP1 on WIN NT.
Please help me out in this issue.
Thanks in advance.
Sapan

Similar Messages

  • Explicity mapping between ActionScript and Java objects for the BlazeDS Messaging Service

    The BlazeDS documentation shows how to explicitly map between ActionScript and Java objects. For example, this works fine for RPC services, e.g.
    import flash.utils.IExternalizable;
    import flash.utils.IDataInput;
    import flash.utils.IDataOutput;
    [Bindable]
    [RemoteClass(alias="javaclass.User")]
    public class User implements IExternalizable {
            public var id : String;
            public var secret : String;
            public function User() {
            public function readExternal(input : IDataInput) : void {
                    id = input.readObject() as String;
            public function writeExternal(output : IDataOutput) : void {
                    output.writeObject(id);
    and
    import java.io.Externalizable;
    import java.io.IOException;
    import java.io.ObjectInput;
    import java.io.ObjectOutput;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    public class User implements Externalizable {
        protected String id;
        protected String secret;
        public String getId() {
            return id;
        public void setId(String id) {
            this.id = id;
        public String getSecret() {
            return secret;
        public void setSecret(String secret) {
            this.secret = secret;
        public void readExternal(ObjectInput in) throws IOException,
                    ClassNotFoundException {
            id = (String) in.readObject();
        public void writeExternal(ObjectOutput out) throws IOException {
            out.writeObject(id);
    If I called an RPC service that returns a User, the secret is not sent over the wire.  Is it also possible to do this for the messaging service? That is, if I create a custom messaging adapter and use the function below, can I also prevent secret from being sent?
    MessageBroker messageBroker = MessageBroker.getMessageBroker(null);
    AsyncMessage message = new AsyncMessage();
    message.setDestination("MyMessagingService");
    message.setClientId(UUIDUtils.createUUID());
    message.setMessageId(UUIDUtils.createUUID());
    User user = new User();
    user.setId("id");
    user.setSecret("secret");
    message.setBody(user);
    messageBroker.routeMessageToService(message, null);

    Hi Martin. The way that AMF serialization/deserialization works for BlazeDS is the same regardless of which service is being used, so yes that code will work for messaging as well. On the server, the serialization/deserialization of messages happens at the endpoint. For an incoming message for example, the endpoint deserializes the message and then hands it off to the MessageBroker which decides which service/destination to deliver the message to.
    That was a good question. Thanks for asking it. Lots of people are used to doing custom serialization/deserialization with the RPC services (RemoteObject/RemotingService) but I'm not sure everyone realizes they can do this for messaging as well.
    -Alex

  • Generation of XML file from Java objects using castor

    I have the following java file(Customer.java).
    public class Customer
         private String ID;
         private FirstName firstName;
         private MiddleName middleName;
         private LastName lastName;
         private ArrayList address;
         public ArrayList getAddress() {
              return address;
         public void setAddress(ArrayList address) {
              this.address = address;
         public FirstName getFirstName() {
              return firstName;
         public void setFirstName(FirstName firstName) {
              this.firstName = firstName;
         public String getID() {
              return ID;
         public void setID(String id) {
              ID = id;
         public LastName getLastName() {
              return lastName;
         public void setLastName(LastName lastName) {
              this.lastName = lastName;
         public MiddleName getMiddleName() {
              return middleName;
         public void setMiddleName(MiddleName middleName) {
              this.middleName = middleName;
    Using castor i have created an xml file(customer.xml) which has the following format.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <customer ID="fbs0001">
    <FIRSTNAME>Fred</FIRSTNAME>
    <MIDDLENAME>B</MIDDLENAME>
    <LASTNAME>Scerbo</LASTNAME>
    - <ADDRESS>
    <FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
    <SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
    </ADDRESS>
    - <ADDRESS>
    <FIRSTLINE>ITPL</FIRSTLINE>
    <SECONDLINE>Whitefield Bangalore</SECONDLINE>
    </ADDRESS>
    </customer>
    I have used a mapping file to get this output.Is there a way where i can get the output xml in the following format without changing the Java object structure.If yes then please suggest how this can be done.
    <?xml version="1.0" encoding="UTF-8" ?>
    - <customer ID="fbs0001">
    <FIRSTNAME>Fred</FIRSTNAME>
    <MIDDLENAME>B</MIDDLENAME>
    <LASTNAME>Scerbo</LASTNAME>
    </customer>
    <ADDRESS>
    <FIRSTLINE>No 18, Sheshadri road</FIRSTLINE>
    <SECONDLINE>Gandhinagar Bangalore</SECONDLINE>
    </ADDRESS>
    - <ADDRESS>
    <FIRSTLINE>ITPL</FIRSTLINE>
    <SECONDLINE>Whitefield Bangalore</SECONDLINE>
    </ADDRESS>
    I mean the output xml file should have the address as a separate tag not withing the root tag customer.

    Hello,
    Castor's own discussion groups might be able to point you to the solution you're looking for (if this use case is possible using Castor).
    Oracle has its own object-to-XML mapping tool that is part of the TopLink product. It allows you to map existing objects to an existing XML Schema. This can be done visually using the TopLink Workbench, or programmatically using the TopLink APIs. TopLink OXM also supports the JAXB specification.
    Using TopLink OXM to get the desired XML result I would recommend the following. Map the Customer and Address classes to XML, but don't map the relationship between Customer and Address. Then make the calls to the marshaller something like the following:
    marshaller.marshal(aCustomer, System.out);
    for(int x=0; x<aCustomer.getAddress().size(); x++) {
         marshal(aCustomer.getAddress().get(x), System.out);
    Example - Using TopLink OXM to map an existing object model to an existing XML Schema:
    http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/howto/ox/index.htm
    For more information on TopLink object-to-XML mapping:
    http://www.oracle.com/technology/products/ias/toplink/preview/10.1.3dp4/objectxml/index.html
    -Blaise

  • Map XML tag to an object style

    Hi everyone!
    I am not sure this is the correct place to post it, but i didn't find any "tagging" department of the forums.
    I do import some XML into ID document.
    Text nodes of my XML are imported properly, and i can map any tag of XML to one of the paragraph or table styles.
    But, when i import any images (or another ID documents) with <... href="..." />, how can i map that tag to an object style?
    ///////////// It would be very helpful for example when i'm going to set the stroke of 1pt to all of inline images of text frame.
    Please any feedback would be helpful.
    Alex.

    I will try to give an example, just to give a kick start ........... you need little bit of tweaking to meet your actual requirement:
    suppose you have an xml element "tag" having an attribute "@href" with object style name defined as  it's value. 
    <tag href="object_style_name">
    "object_style_name" is a object style and should exist in your document. To map the tag with the corresponding object style value you can use XMLRules in JS:
    //NOTE: NOT TESTED, BUT SHOULD WORK
    #include "glue code.jsx"
    main();
    function main(){
    if (app.documents.length != 0){
    var myDoc = app.activeDocument;
    var myRuleSet = new Array (
    new findObjAttribute("//*[@href]")
    with(myDoc){
    var elements = xmlElements;
    __processRuleSet(elements.item(0), myRuleSet);
    else{
    alert("You have no document open!");
    exit();
    function findObjAttribute(XPATH){
    this.name = "findObjAttribute";
    this.xpath = XPATH;
    this.apply = function(myElement, myRuleProcessor)
    //Just to check whether the collect element is selected
    var elmName=myElement.markupTag.name;
    var styleName=myElement.xmlAttributes.itemByName("href").value;
    with(myElement){
    try {
    applyObjectStyle(myDoc.objectStyles.item(styleName), true);
         } catch(e){};
    return true;
    HTH,
    Pankaj Chaturvedi

  • Reg XML generation from java objects using SAX 2.0

    i'm using java 1.6 and i've imported following class to generate XML from java objects
    import com.sun.org.apache.xml.internal.serialize.OutputFormat;
    import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
    the following class has been imple her to create a Xml file and tag elements ,
    OutputFormat of = new OutputFormat("XML", "iso-8859-1", true);
    XMLSerializer serializer = new XMLSerializer(fos, of);
    ContentHandler hd = serializer.asContentHandler();
    hd.startDocument();
    everything works fine but i'm getting warrnin reg the serializer and outputformat
    warring is:
    com.sun.org.apache.xml.internal.serialize.OutputFormat is Sun proprietary API and may be removed in a future release
    com.sun.org.apache.xml.internal.serialize.OutputFormat is Sun proprietary API and may be removed in a future release
    HOW CAN I AVOID DS WARRING PLZ HELP REG DS
    thanks ,
    with regards,
    Rajesh.S

    I've been having the same problem. Here is what i found:
    [http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6476630]
    Hope that helps (or at least helps you feel better).

  • Problem in casting a database object to Java object

    hi everyone,
    Iam trying to execute following example which was provided in oracle documentation. iam planning to implement this concept in my project...But, i am not able to run...iam herewith enclosing the sample code and its error...Kindly help me out
    import java.sql.*;
    import java.io.*;
    import java.util.*;
    import java.math.BigDecimal;
    import oracle.sql.*;
    import oracle.jdbc.*;
    public class PersonObject
    public static void main (String args [])
    throws Exception
    // Register the Oracle JDBC driver
    DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
    // Connect to the database
    // You need to put your database name after the @ sign in
    // the connection URL.
    // The sample retrieves an object of type "STUDENT",
    // materializes the object as an object of type ADT.
    // The Object is then modified and inserted back into the database.
    Connection conn =
    DriverManager.getConnection ("jdbc:oracle:thin:@raman.monsanto.com:1521:ramdevl","multispec", "mspec");
    // It's faster when auto commit is off
    conn.setAutoCommit (false);
    // Create a Statement
    Statement stmt = conn.createStatement ();
    try
    stmt.execute ("drop table people");
    stmt.execute ("drop type PERSON FORCE");
    stmt.execute ("drop type ADDRESS FORCE");
    catch (SQLException e)
    System.out.println("Error during executing a statement: "+ e);
    stmt.execute ("create type ADDRESS as object (street VARCHAR (30), num NUMBER)");
    stmt.execute ("create type PERSON as object (name VARCHAR (30), home ADDRESS)");
    stmt.execute ("create table people (empno NUMBER, empid PERSON)");
    stmt.execute ("insert into people values(101, PERSON ('Greg', ADDRESS ('Van Ness', 345)))");
    stmt.execute ("insert into people values(102, PERSON ('John', ADDRESS ('Geary', 229)))");
    ResultSet rs = stmt.executeQuery ("select * from people");
    System.out.println("This application works till extraction of data\n");
    showResultSet (rs);
    rs.close();
    stmt.close();
    conn.close();
    public static void showResultSet (ResultSet rs)
    throws SQLException
    while (rs.next ())
    ResultSetMetaData rsmd=rs.getMetaData();
    System.out.println("the no of columns: "+rsmd.getColumnCount());
    for(int i=0;i<rsmd.getColumnCount();i++)
    System.out.println("The column no "+(i+1)+"is of type: "+rsmd.getColumnTypeName(i+1) );
    int empno = rs.getInt (1);
    // retrieve the STRUCT
    (This line throws the error----->) STRUCT person_struct = (STRUCT)rs.getObject (2);
    Object person_attrs[] = person_struct.getAttributes();
    System.out.println ("person name: " + (String) person_attrs[0]);
    STRUCT address = (STRUCT) person_attrs[1];
    System.out.println ("person address: ");
    Object address_attrs[] = address.getAttributes();
    System.out.println ("street: " + (String) address_attrs[0]);
    System.out.println ("number: " +
    ((BigDecimal) address_attrs[1]).intValue());
    System.out.println ();
    The error message is as follows:
    sj -make -cdb newmodeltest.cdb -g -d D:\VisualCafe\Projects\ -classpath
    D:\jdk1.3\jre\lib\classes12.zip;D:\VisualCafe\Projects\;D:\VISUALCAFE\JAVA\LIB\;D:\VISUALCAFE\JAVA\LIB\SYMCLASS.ZIP;D:\VISUALCAFE\JAVA\LIB\CLASSES.ZIP;D:\VISUALCAFE\JFC\SWINGALL.JAR;D:\VISUALCAFE\swing
    -1.1\SWINGALL.JAR;D:\VISUALCAFE\JAVA\LIB\RT.JAR;D:\VISUALCAFE\BIN\COMPONENTS\SFC.JAR;D:\VISUALCAFE\BIN\COMPONENTS\SYMBEANS.JAR;D:\VISUALCAFE\JAVA\LIB\icebrowserbean.jar;D:\VISUALCAFE\JAVA\LIB\jsdk.jar;
    D:\VISUALCAFE\JAVA\LIB\SYMTOOLS.JAR;D:\VISUALCAFE\BIN\COMPONENTS\TEMPLATES.JAR D:\VisualCafe\Projects\PersonObject.java
    Build Successful
    loading PersonObject.class for debugging...
    PersonObject.class successfully loaded
    This application works till extraction of data
    the no of columns: 2
    The column no 1is of type: NUMBER
    The column no 2is of type: MULTISPEC.PERSON
    java.lang.IncompatibleClassChangeError: class java.util.Hashtable does not implement interface java.util.Map
    at oracle.sql.StructDescriptor.getClass(StructDescriptor.java:418)
    at oracle.sql.STRUCT.toJdbc(STRUCT.java:365)
    at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:4195)
    at oracle.jdbc.driver.OracleStatement.getObjectValue(OracleStatement.java:4123)
    at oracle.jdbc.driver.OracleResultSetImpl.getObject(OracleResultSetImpl.java:401)
    at PersonObject.showResultSet(PersonObject.java:106)
    at PersonObject.main(PersonObject.java:54)
    at symantec.tools.debug.MainThread.run(Agent.java:48)
    Thanks in advance
    Sudarshan.K

    Since that implementation has existed since 1.2 and
    the original post suggested that 1.3 was being used,I
    don't see that a newer version would help any.That's not a good assumption. There could have been a
    bug fix.
    Could be. But for the particular error (IncompatibleClassChangeError) I would consider the chance almost non-existent until all other possibilities have been exhausted.

  • Not able to convert SOAP object to java object

    Hi,
    I was able to get SOAP Response, but in that response string field is not able to be transformed into java object.
    Can you be able to give suggestion to solve this problem.
    Thanks in advance,

    Hi,
    You need to provide an example value that's failing and the date formats in the reference data you're using. It's more than likely you don't have the correct format in your ref data.
    regards,
    Nick

  • XML DOM to Java object

    This is probably the wrong forum. I am trying to get up to speed with this fast. I looked at the JAXP tutorial but it does not help with this. (It does provide a quick tutorial on the Swing JTree, however ;-) ... )
    Anyway I can find any number of examples on displaying the entire DOM as a heirarchy, which I do not care about. I want to pull out parts of a DOM tree and create objects using the data (TEXT node values). I know this is a common task and I feel dumb but I am hoping to start somewhere better than the JAXP stuff ... maybe I'm wrong ...
    Can anyone please tell me where to get started learning ?
    Appreciate it !!!

    I am not sure if I am following what you are asking, but maybe this is worth a shot. If you want to just get specific values from an xml file (ie, elements or attributes) here is an example using the dom.
    Hope it helps
    DocumentBuilderFactory docBuildFactory = DocumentBuilderFactory.newInstance();
                            DocumentBuilder docBuilder = docBuildFactory.newDocumentBuilder();
                            Document doc = docBuilder.parse(new File(filename + "\\" + xml));                       
                            //get the root of the document which is the template name
                            doc.getDocumentElement().normalize();
                            String rootName =  doc.getDocumentElement().getNodeName();                       
                            //get elements of data needed
                            NodeList node1 = doc.getElementsByTagName("Memid");
                            Element element1 = (Element)node1.item(0);
                            memberid = element1.getFirstChild().getNodeValue();Sorry if this is not what you are looking for.....

  • How to generate Java objects from XML files with out  scema compilation

    Dear participants,
    My name is Raghavendra , i have a requirement of reading XML files Dynamically and parse them and create java types for manipulation . i will not be provided with sxd files (no schema compilation )coz no one knows how many types of structures are there. i want a generic solution. Please Help.
    Thanks ,
    Raghavendra Ach
    you can mail me to " [email protected]"

    georgemc wrote:
    You could also look at something like Apache Digester, which will parse your XML and populate Java objects with the data. A slightly steeper learning curve than the lower-level APIs such as JDOM, but that's outweighed by the lesser development effortdon't think that would work for the original problem, which seemed to indicate that the xml had an unknown structure.

  • XML to java object AND Performance

    Hi,
    I read some article about marshalling a XML file to Java Object (like Castor, XML Beans projects...)
    To resume: I would like to marshal a XML doc (from XML to Java object. Later I would like to put these objects on a SGBD...). Unfortenaly I suppose that approach is to expensive on term of performance? Supposing that my xml doc contain 100 data's occurances, XML bean woulkd create 100 objects corresponding. My problem is that I don't want that the all 100 objects live in the same time on memory. For example, my code will read sequential, the xml occurances (like a Sax parser), create 10 datas objects (standby), put these in the data base, and destroy these objects before...iteratively create the next 10 objects...
    It is possible ? Can anybody help me?
    Thank

    On the article: Java Architecture for XML Binding (JAXB)
    (http://java.sun.com/developer/technicalArticles/WebServices/jaxb/)
    I found maybe a response?
    "...in other words, you can do a SAX parse of a document and then pass the events to JAXB for unmarshalling. "
    But somebody could help me to write the code to do that?

  • Issue with mapping XML to Java using SAX API

    I am using SAX API to Map XML Documents To Java. Is it possible to differentiate the elements based on the attribute rather than localname or element name in SAX API? because I am having the below xml structure. In SAX API we are processing the element values based on start/End Element name.
    <?xml version="1.0" encoding="UTF-8"?>
    <response>
    <result name="response">
    <doc>
    <str name="art_id">192201910</str>
    <str name="title">test</str>
    <arr name="author">
    <str>Darrell Dunn</str>
    <str>William </str>
    </arr>
    <arr name="tax">
    <str>113243335</str>
    <str>233454666</str>
    </arr>
    </doc>
    <doc>
    <str name="art_id">192201911</str>
    <str name="title">test2</str>
    <arr name="author">
    <str>Darrell Dunn1</str>
    <str>William 1</str>
    </arr>
    </doc>
    </result>
    </response>
    I want to map the elements based on attributes such as
    classobj.art_id, classobj.title, classobj.tax[]. I have wriiten code below, but I am not getting the proper result.
    import org.xml.sax.;
    import org.xml.sax.helpers.;
    import java.io.;
    import java.util.;
    import common.;
    public class XmltoObjectHandler extends DefaultHandler{
    /* Creates a new instance of XmltoObjectHandler */
    public XmltoObjectHandler() {
    // Local SolrDocument object to collect
    // document XML data.
    private XmlDocument doc = new XmlDocument();
    // Local list of solr documents items...
    private Vector xmlDocuments = new Vector();
    // Local current solr document reference...
    private XmlDocument currentSolrDoc;
    // Buffer for collecting data from
    // the "characters" SAX event.
    private CharArrayWriter contents = new CharArrayWriter();
    // Override methods of the DefaultHandler class
    // to gain notification of SAX Events.
    // See org.xml.sax.ContentHandler for all available events.
    public void startElement( String namespaceURI,
    String localName,
    String qName,
    Attributes attr ) throws SAXException {
    if ( localName.equals( "doc" ) ) {
    currentXmlDoc = new XmlDocument();
    solrDocuments.addElement( currentSolrDoc );
    if( localName.equals("str"){
    for ( int i = 0; i < attr.getLength(); i++ ){
    if("art_id".equals(attr.getValue(i))){
    currentSolrDoc.art_id = contents.toString();
    if("title".equals(attr.getValue(i))){
    currentSolrDoc.title = contents.toString();
    public void endElement( String namespaceURI,
    String localName,
    String qName ) throws SAXException {
    public void characters( char[] ch, int start, int length )
    throws SAXException {
    contents.write( ch, start, length );
    public Vector getxmlDocuments() {
    return solrDocuments;
    public static void main( String[] argv ){
    System.out.println( "Example4:" );
    try {
    // Create SAX 2 parser...
    XMLReader xr = XMLReaderFactory.createXMLReader();
    // Set the ContentHandler...
    XmltoObjectHandler ex4 = new XmltoObjectHandler();
    xr.setContentHandler( ex4 );
    // Parse the file...
    xr.parse( new InputSource(new FileReader( "xmlfile.xml" )));
    // Display all documents items...
    XmlDocument i;
    Vector items = ex4.getxmlDocument();
    Enumeration e = items.elements();
    while( e.hasMoreElements()){
    i = (XmlDocument) e.nextElement();
    System.out.println(i.art_id+"\n");
    System.out.println(i.title+"\n");
    }catch ( Exception e ) {
    e.printStackTrace();
    Can anybody help me how to process this type of xml. Is there any other way we can do this? I am trying for two days. It is a big deadlock for me. any help greatly appriciated. Thanks in advance.

    I added my code inside code tags...
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    import java.io.*;
    import java.util.*;
    import common.*;
    public class XmltoObjectHandler extends DefaultHandler{
        /** Creates a new instance of XmltoObjectHandler */
        public XmltoObjectHandler() {
        // Local SolrDocument object to collect
        // document XML data.
        private XmlDocument doc = new XmlDocument();
        // Local list of solr documents items...
        private Vector xmlDocuments = new Vector();
        // Local current solr document reference...
        private XmlDocument currentSolrDoc;
        // Buffer for collecting data from
        // the "characters" SAX event.
        private CharArrayWriter contents = new CharArrayWriter();  
        // Override methods of the DefaultHandler class
        // to gain notification of SAX Events.
        // See org.xml.sax.ContentHandler for all available events.
        public void startElement( String namespaceURI,
                String localName,
                String qName,
                Attributes attr ) throws SAXException {
              if ( localName.equals( "doc" ) ) {
                currentXmlDoc = new XmlDocument();
                solrDocuments.addElement( currentSolrDoc );
              if( localName.equals("str"){
                   for ( int i = 0; i < attr.getLength(); i++ ){               
                    if("art_id".equals(attr.getValue(i))){
                             currentSolrDoc.art_id = contents.toString();
                        if("title".equals(attr.getValue(i))){
                             currentSolrDoc.title = contents.toString();
        public void endElement( String namespaceURI,
                String localName,
                String qName ) throws SAXException {      
        public void characters( char[] ch, int start, int length )
        throws SAXException {       
            contents.write( ch, start, length );       
        public Vector getxmlDocuments() {
            return solrDocuments;
        public static void main( String[] argv ){       
            System.out.println( "Example4:" );
            try {          
                // Create SAX 2 parser...
                XMLReader xr = XMLReaderFactory.createXMLReader();           
                // Set the ContentHandler...
                XmltoObjectHandler ex4 = new XmltoObjectHandler();
                xr.setContentHandler( ex4 );           
                // Parse the file...
                xr.parse( new InputSource(new FileReader( "xmlfile.xml" )));          
                // Display all documents items...
                XmlDocument i;
                Vector items = ex4.getxmlDocument();
                Enumeration e = items.elements();
                while( e.hasMoreElements()){
                    i = (XmlDocument) e.nextElement();
                    System.out.println(i.art_id+"\n");
                        System.out.println(i.title+"\n");
            }catch ( Exception e ) {
                e.printStackTrace();
    }

  • XMl and Java object mapping

    I need to map java objects with XMl Node or XML Elements.
    My java objets get some attributes, for instance name,color ...
    and i need an output like:
    <OBJECT_OF_TYPE_XXX>
    <NAME>scott</NAME>
    <COLOR>red</COLOR>
    </OBJECT_OF_TYPE_XXX>
    Any idea?
    Thanks
    Maurice

    You can try JAXB which includes a compiler that generates classes based on the XML Schema for your xml structure. It also features the possibility to convert between xml and the generated objects.
    Take a look at chapter 9 and 10 at http://java.sun.com/webservices/docs/1.1/tutorial/doc/index.html

  • Parse of a xml file to an java object model

    Hello,
    I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
    I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
    Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
    public static void readFile(String root){
              DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   String contents = scanner.next();
                   scanner.close();
                   Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
                   Node node = null;
                   NodeList nodes = null;
                   Element element = document.getDocumentElement();
                   System.out.println(element.getNodeName());
                   NodeList subNodes;
                   NamedNodeMap attributes;
                   //if (element.hasAttributes())
                   visitNodes(element);
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         private static void visitNodes (Node node){
              for(Node childNode = node.getFirstChild(); childNode!=null;){
                   if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                        System.out.println("Document node Name " + childNode.getNodeName());
                        visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                        System.out.println("Node Name " + childNode.getNodeName());
                        if (childNode.hasAttributes()){
                             visitAttributes(childNode.getAttributes());
                        if (childNode.hasChildNodes()){
                             visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                        System.out.println("Node value " + childNode.getNodeValue());
                   Node nextChild = childNode.getNextSibling();
                   childNode = nextChild;
         private static void visitAttributes(NamedNodeMap attributes){
              Node node;
              for(int i = 0; i < attributes.getLength(); i++){
                   node = attributes.item(i);
                   System.out.print(node.getNodeName() + " ");
                   System.out.print(node.getNodeValue() + " ");
                  }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
    But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
    Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
    When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
    Have you any other suggestions? All the help or idea will be well received.
    Thanks for all.

    Hello again,
    My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
    I have solved my initial problem with the xml parser.
    Firstly, I read the complete XML file, validated previously.
    The code I've used is this:
    public static String readCompleteFile (String root){
              String content = "";
              try {
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   content = scanner.next();
                   scanner.close();
              } catch (IOException e) {
                   e.printStackTrace();
              return content;
         }Now, I've the file in memory and I hope I can explain me better.
    I can receive different types of XML that could be or not partly equals.
    For this purpose I've created an external jar library with all the possible objects contained in my xml files.
    Each one of this objects depend on other, until found leaf nodes.
    For example, If I receive one xml with a scheme like the next:
    <Person>
        <Name>Juliet</Name>
        <Father Age="30r">Peter</Father>
        <Mother age="29">Theresa</Mother>
        <Brother>
        </Brother>
        <Education>
            <School>
            </school>
        </education>
    </person>
    <person>
    </person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
    The method that I must implement as constructor in every object is similar to this:
    public class Person{
      final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
      private String name;
         private Father father;
         private Mother mother;
         private ArrayList brothers;
         private Education education;
         public Person(String xml){
           XmlUtil utilXml = new XmlUtil();          
              String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
              String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
              String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
              String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
              if (!xmlFather.equals("")){
                   this.setFather(new Father(xmlFather));
              if (!xmlMother.equals("")){
                   this.setMother(new Father(xmlMother));
              if (!xmlBrothers.equals("")){
                ArrayList aux = new ArrayList();
                String xmlBrother;
                while xmlBrothers != null && !xmlBrothers.equals("")){
                  xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
                  aux.add(new Brother(xmlBrother);
                  xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
                this.setBrothers(aux);
              if (!xmlEducation.equals("")){
                   this.setEducation(new Father(xmlEducation));     
    }If the object is a leaf object, the constructor will be like this:
    public class Mother {
         //Elements
         private String name;
         private String age;
         public Mother(String xml){          
              XmlUtil utilXml = new XmlUtil();
              HashMap objects = utilXml.parsearString(xml);
              ArraysList objectsList = new ArrayList();
              String[] Object = new String[2];
              this.setName((String)objects.get("Mother"));
              if (objects.get("attributes")!= null){
                   objectsList = objects.get("attributes");
                   for (int i = 0; i < objectsList.size();i++){
                     Object = objectsList.get(i);
                     if (object[0].equals("age"))
                       this.setAge(object[1]);
                     else
         }Each class will have its getter and setter but I do not have implemented in the examples.
    Finally, the parser is as follows:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    public class XmlUtil {
         public HashMap parsearString(String contenido){
              HashMap objet = new HashMap();
              DocumentBuilderFactory factory;
              DocumentBuilder builder;
              Document document;
              try{
                   if (content != null && !content.equals("")){
                        factory = DocumentBuilderFactory.newInstance();
                        builder = factory.newDocumentBuilder();
                        document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                        object = visitNodes(document);                    
                   }else{
                        object = null;
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
                   return null;
              } catch (SAXException e) {
                   e.printStackTrace();
                   return null;
              } catch (IOException e) {
                   e.printStackTrace();
                   return null;
              return object;
         private HashMap visitNodes (Node node){
              String nodeName = "";
              String nodeValue = "";
              ArrayList attributes = new ArrayList();
              HashMap object = new HashMap();
              Node childNode = node.getFirstChild();
              if (childNode.getNodeType() == Node.ELEMENT_NODE){
                   nodeName = childNode.getNodeName();                    
                   if (childNode.hasAttributes()){
                        attributes = visitAttributes(childNode.getAttributes());
                   }else{
                        attributes = null;
                   nodeValue = getNodeValue(childNode);
                   object.put(nodeName, nodeValue);
                   object.put("attributes", attributes);
              return object;
         private static String getNodeValue (Node node){          
              if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
                   return node.getFirstChild().getNodeValue();
              else
                   return "";
         private ArrayList visitAttributes(NamedNodeMap attributes){
              Node node;
              ArrayList ListAttributes = new ArrayList();
              String [] attribute = new String[2];
              for(int i = 0; i < attributes.getLength(); i++){
                   atribute = new String[2];
                   node = attributes.item(i);
                   if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                        attribute[0] = node.getNodeName();
                        attribute[1] = node.getNodeValue();
                        ListAttributes.add(attribute);
              return ListAttributes;
    }This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
    The code I use is:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class UtilClasses {
         public Object UtilClasses(String package, String object, String xml){
              try {
                Class class = Class.forName(package + "." + object);
                //parameter types for methods
                Class[] partypes = new Class[]{Object.class};
                //Create method object . methodname and parameter types
                Method meth = class.getMethod(object, partypes);
                //parameter types for constructor
                Class[] constrpartypes = new Class[]{String.class};
                //Create constructor object . parameter types
                Constructor constr = claseObjeto.getConstructor(constrpartypes);
                //create instance
                Object obj = constr.newInstance(new String[]{xml});
                //Arguments to be passed into method
                Object[] arglist = new Object[]{xml};
                //invoke method!!
                String output = (String) meth.invoke(dummyto, arglist);
                System.out.println(output);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
              return null;
         }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
    I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
    greetings.

  • How to bind dynamic xml with Java objects without xsd

    have a question, and hope someone here can help me.
    In my current project, I will get a xml file, containing some information of each user, and map them into a set of user objects.
    For each user, there are some fixed attributes, such as name, phone#, age, position, etc. The problem is, client can customize, and add new attibutes, such as address, favorite color, so there will be no xsd for the xml.
    What I want to do, is map fixed attributes to user object attributes, for example, name attribute to User.name, and they will have corresponding getters, and setters, but for custom attributes, I want to add them to a HashMap in User object, for example, use string "ADDRESS" as the key, and address as the value.
    Is there any way I can do this? Thank you very much for any help you can provide.

    It would not be too hard to do in regular code.
    First, make a HashSet with the Strings for the names of the known attributes that will be processed with setters.
    Then, get the NamedNodeMap via getAttributes(). That will give you all attributes -- both the ones you will handle with your setters and the ones you will handle via a HashMap.
    Then, loop through the NamedNodeMap. For each attribute, get the name and value. If the name is in the HashSet of known values, process it with a list of
    if ( attName.equals( "name" ))
        whatever.setName( value );
       continue;
    }If it is not in the HashSet, then set the value into your HashMap with the name and value.
    There is no standard way to do this.
    Dave Patterson

  • How to parse XML to Java object... please help really stuck

    Thank you for reading this email...
    If I have a **DTD** like:
    <!ELEMENT person (name, age)>
    <!ATTLIST person
         id ID #REQUIRED
    >
    <!ELEMENT name ((family, given) | (given, family))>
    <!ELEMENT age (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT given (#PCDATA)>
    the **XML** like:
    <person id="a1">
    <name>
         <family> Yoshi </family>
         <given> Samurai </given>
    </name>
    <age> 21 </age>
    </person>
    **** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
    Thank you for your help, Yo

    Hi, Yo,
    Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
    A bit more question for dear people:
    In the notes, it's mainly focus on JAXB,
    1. Is that mean JAXB is most popular parser for
    parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
    1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
    2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
    3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
    Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
    A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
    When parser job is done,
    what kind of Java Object we will get? (String,
    InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
    2. If we want to use JAXB, we have to contain a
    XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
    I am very new to XML, is there any simpler way to get
    around them? It has already take me 4 days to find a
    simple parser which give it XML and DTD, then return
    to me Java objects ... I mean if that kind of parser
    exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
    Jan

Maybe you are looking for