XML Representation

Hi all,
Need some advice on how to represent Java objects as XML and vice-versa. Apache's Commons Betwixt seems to be a good bet. I wanted to know if there are any other tools available. Briefly, in my Service's save() I receive Java objects, convert them to xml and then store them as an xml in the database. Occasionally, some tinkering with the xml may be required in a load() call. Wanted to know which API will be best suited for this.
Thanks

Oh, there are so many different Java to XML and vice versa mappers.
Castor is one that's quite well-known.
JAXB (Java Architecture for XML Binding) is a standard method.
Try searching Google for "java xml data binding" for more answers.

Similar Messages

  • Generating an XML representation of arbitrary Java objects

    Hi. Just for fun, I'm attempting to write some code which creates an XML representation of an arbitrary java object using reflection. The idea is that only properties with get/set methods should come through in the XML.
    Here is the code:
    package com.uhg.aarp.compas.persistence.common.xml;
    import java.io.IOException;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.FactoryConfigurationError;
    import javax.xml.parsers.ParserConfigurationException;
    import org.xml.sax.SAXException;
    import org.xml.sax.SAXParseException;
    import org.w3c.dom.Document;
    import org.w3c.dom.DOMException;
    import org.w3c.dom.Node;
    import java.util.Stack;
    public class XMLDAO {
         public static String getXMLWithHeader(Object obj){
              return "<?xml version=\"0\"?>" + getXML(obj);
          * Returns an XML representation of an arbitrary object
         public static String getXML(Object obj){
              StringBuffer buffer = new StringBuffer();
              AccessorMethod[] accessorMethods = getAccessorMethods(obj);
              buffer.append("<" + obj.getClass().getName() + ">\n");
              //List
              if(obj instanceof List){
                   List objList = (List)obj;
                   Iterator iterator = objList.iterator();
                   while(iterator.hasNext()){                              
                        buffer.append(getXML(iterator.next()));
              else{
                   for(int i = 0; i < accessorMethods.length; i++){
                        Object fieldObj = null;
                        try{
                             fieldObj = accessorMethods.invoke();
                             1. Primitive Wrapper or String(base case)
                             if(fieldObj instanceof Integer || fieldObj instanceof Float || fieldObj instanceof Double
                                  || fieldObj instanceof Long || fieldObj instanceof String){
                                  buffer.append("<" + accessorMethods[i].getAccessorFieldName() + ">");
                                  buffer.append(accessorMethods[i].invoke());
                                  buffer.append("</" + accessorMethods[i].getAccessorFieldName() + ">\n");
                             else if(fieldObj instanceof Object[]){
                                  buffer.append("<" + accessorMethods[i].getAccessorFieldName() + ">\n");
                                  Object[] fieldArray = (Object[])fieldObj;
                                  for(int j = 0; j < fieldArray.length; j++)
                                       buffer.append(getXML(fieldArray[i]));
                                  buffer.append("</" + accessorMethods[i].getAccessorFieldName() + ">\n");
                        }catch(Exception e){
                             System.out.println("Couldn't invoke method: " + accessorMethods[i].getName());
              buffer.append("</" + obj.getClass().getName() + ">\n");
              return buffer.toString();
         * Returns the Object representation for the XML - used to rebuild Java objects
         * converted to XML by XMLDAO.getXML().
         public static Object getObject(String xmlString) throws ParserConfigurationException,
              SAXException, IOException{
              //the root element is the class name
              DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
              DocumentBuilder builder = factory.newDocumentBuilder();
              Document document = builder.parse(xmlString);
              Stack objectStack = new Stack();
              return getObject(document);
         private static Object getObject(Node n){
              //every document is either an object or a bean property
              //all bean properties have values
              //no object has a value, it can only have bean properties
              //the base case occurs when the document has a value
              String nodeName = n.getNodeName();
              if(n.getNodeValue() == null){
                   System.out.println("node " + nodeName + " is an object");
              else{
                   System.out.println("node " + nodeName + " is a bean property");
              return null;
         * Returns all of the "getter" methods for the given object
         private static AccessorMethod[] getAccessorMethods(Object obj){
              Class theClass = obj.getClass();
              Method[] objMethods = theClass.getMethods();
              ArrayList methodList = new ArrayList();
              for(int i = 0; i < objMethods.length; i++){
                   try{
                        methodList.add(new AccessorMethod(obj, objMethods[i]));
                   }catch(IllegalArgumentException e){}
              return (AccessorMethod[])methodList.toArray(new AccessorMethod[methodList.size()]);
         * Invokes the specified "getter" method and returns the result as an Object
         private Object invokeAccessorMethod(Object obj, Method m) throws IllegalAccessException,
              InvocationTargetException{
              return m.invoke(obj, null);
    package com.uhg.aarp.compas.persistence.common.xml;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    * Represents an AccessorMethod (i.e. getField()) on an Object
    public class AccessorMethod{
         private Object obj;
         private Method m;
         private String accessorFieldName;
         * Constructor for AccessorMethod
         public AccessorMethod(Object obj, Method m) throws IllegalArgumentException{
              1. Method name starts with get
              2. Method name does not equal get
              3. Method takes no arguments
              4. Method return type is not void
              String methodName = m.getName();
              if(methodName.indexOf("get") != 0 || methodName.length() == 3 &&
                   m.getParameterTypes().length != 0 && m.getReturnType() != null){
                   throw new IllegalArgumentException("Not a valid getter method " + methodName);
              this.obj = obj;
              this.m = m;
              String tempName = m.getName().substring(3, m.getName().length());
              this.accessorFieldName = Character.toLowerCase(tempName.charAt(0)) + tempName.substring(1, tempName.length());
         public Object invoke() throws IllegalAccessException, InvocationTargetException{
              return m.invoke(obj, null);
         * Gets the m
         * @return Returns a Method
         public Method getM() {
              return m;
         * Sets the m
         * @param m The m to set
         public void setM(Method m) {
              this.m = m;
         * Gets the accessorFieldName
         * @return Returns a String
         public String getAccessorFieldName() {
              return accessorFieldName;
         * Sets the accessorFieldName
         * @param accessorFieldName The accessorFieldName to set
         public void setAccessorFieldName(String accessorFieldName) {
              this.accessorFieldName = accessorFieldName;
         * Gets the obj
         * @return Returns a Object
         public Object getObj() {
              return obj;
         * Sets the obj
         * @param obj The obj to set
         public void setObj(Object obj) {
              this.obj = obj;
         public String getName(){
              return this.m.getName();
    I'm having some trouble figuring out how to implement the XMLDAO.getObject(Node n) method. I was thinking of maintaining a Stack of the previous Objects as I traverse the DOM, but I think that might be unnecessary work. Basically I'm wondering how I determine what the last "object" is in the DOM from any given node. Anyone have any input?

    I think the end of my post got cut off:
    I'm having some trouble figuring out how to implement the XMLDAO.getObject(Node n) method. I was thinking of maintaining a Stack of the previous Objects as I traverse the DOM, but I think that might be unnecessary work. Basically I'm wondering how I determine what the last "object" is in the DOM from any given node. Anyone have any input?

  • Xml representation of a string

    hi all,
    how do i make an xml representation of a string..if anyone knows please post it.
    thanks

    wow, you guys must be all in the same class, that's 3 times this question has been asked. Look below...

  • Discussion of xml representation types

    I have a discussion with a college about representations of xml data to be passed between webservice and client applications.
    My Suggestion: org.w3c.dom.Document - as it appears most "modern" ways/apis or parsing xml take this as a native input and there would be no need to convert to an inputSource or other type.
    Other Suggestion: A String object - supposedly because it is generic enough to be used by others.

    I would still follow the standards. Serialize the XML to bytes. I don't see any point in treating so-called "internal" applications differently, it just makes it harder for people to maintain them in the future.
    Besides, there's a rule that I call the "HMS Pinafore" rule of system design:
    Chorus: What, never?
    Singer: No, never!
    Chorus: What, NEVER?
    Singer: ... Hardly ever.

  • XML File Input to Generated Classes

    Hi,
    I looked at the Oracle Class Generator and used it to generate
    some class files for a sample dtd schema that I had. Upon
    looking at the classes that were generated, I saw only APIs to
    construct instances thru regular means (providing values to
    members) and APIs to print the XML representation to an output
    stream.
    However, I this functionality is not as complete as I expected it
    to be. I expected the document class to include a constructor
    that will simply take an XML document object and populate the
    various members automatically. Is this functionality really
    non-existent at this point ? Is it in the works ?
    Let me know
    Arun
    null

    You are correct that the Class Generator does not have this
    functionality at this time as our parser only can build DOM
    trees. We have logged your enhancement request.
    Oracle XML Team
    http://technet.oracle.com
    Oracle Technology Network
    Arun (guest) wrote:
    : Hi,
    : I looked at the Oracle Class Generator and used it to generate
    : some class files for a sample dtd schema that I had. Upon
    : looking at the classes that were generated, I saw only APIs to
    : construct instances thru regular means (providing values to
    : members) and APIs to print the XML representation to an output
    : stream.
    : However, I this functionality is not as complete as I expected
    it
    : to be. I expected the document class to include a constructor
    : that will simply take an XML document object and populate the
    : various members automatically. Is this functionality really
    : non-existent at this point ? Is it in the works ?
    : Let me know
    : Arun
    null

  • Best Practices:: How to generate XML file from a ResultSet

    Hi all,
    Could someone please suggest the best practices of how to generate an XML file from a resultset? I am developing a web application in Java with Oracle database and one of my tasks is to generate an XML file when the user, for example, click a "download as XML" button on the JSP. The application is basically like an Order with line items. I am using Struts and my first thought has been to have an action class which will extend struts's DownloadAction and through StAX's Iterator API to create an XML file. I intend to have a POJO which will have properties of all columns of my order and line items tables so that for each order I get all line items and:
    1. Write order details then
    2. Through an iterator write line items of that order to an XML file.
    I will greatly appreciate for comments or suggestions on the best way to do this through any pointers on the Web.
    alex

    Use a OracleWebRowSet in which an XML representation of the result set may be obtained.
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/files/oracle10g/webrowset/Readme.html
    http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/jcrowset.htm

  • Creating a Business Partner from XML

    I have a problem creating a Business Partner from an XML
    First I did get the XML from an existing one.  Deleted the DocEntry element but I always get this error :
    -5002 : Employee is not a Technician  [OCRD.DfTcnician] , '0'
    Even if I go to this element and put NOTHING, I get the error anyway
    What that means ?

    Yeah, I succeeded.  I had to get rid of dtfncien element completly and DocEntry element too and the bp was created
    Would have been so much useful to get an EMPTY xml representation of an object so we juste have to fill the needed properties to an empty one and create the object afterward.
    According to various threads, we have to GetAsXML() then, change whatever needs to be changed and then we create the object from this xml but there are a lot to get rid of sometimes in these objects

  • Generation of XSD file from existing javax.xml.validation.Schema object

    Hi all.
    Is it possible to obtain the XML representation of Schema object - in other words, decompile it back to schema file, using standard API's?
    Greatly appreciate any inputs,
    Jabb

    Hi all.
    Is it possible to obtain the XML representation of Schema object - in other words, decompile it back to schema file, using standard API's?
    Greatly appreciate any inputs,
    Jabb

  • 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

  • How to create XML string for an object matching the result of a marshal?

    I'm trying to create a XML string representation of an object which exactly matches the XML which results from marshalling the object into a request. I'm almost there except that the XML string I come up with is missing the attribute "standalone=\"yes\"" in the topmost xml element, and this attribute is present in the marshalled XML. I'm using the XML string to create a payload signature which must match exactly with the XML payload of the request, so the two XML representations of the object really do need to be identical.
    Here's what I'm doing to create the XML from the object:
       private String myObjectToXmlString (final MyObject myObject)
           throws Exception {
                 try {
               DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
               Document document = documentBuilder.newDocument();
               myObjectMarshaller.marshal(myObject, document);
               Source source = new DOMSource(document);
               StringWriter stringWriter = new StringWriter();
               Result result = new StreamResult(stringWriter);
               TransformerFactory factory = TransformerFactory.newInstance();
               Transformer transformer = factory.newTransformer();
               transformer.transform(source, result);
               return stringWriter.getBuffer().toString();
           } catch (Exception ex) {
               throw new Exception("Unable to convert a MyObject object to an XML String -- " + ex.toString(), ex);
       }The XML which is produced looks like this:
    <?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <ns2:myObject xmlns:ns2=\"http://sunconnection.sun.com/xml\">
       <myObjectId>0</myObjectId>
       <objectType>1</objectType>
       <description>Test Object</description>
    </ns2:myObject>The payload object is marshalled to the request like so:
        // marshall the MyObject to the output stream
       OutputStream outputStream = myHttpUrlConnection.getOutputStream();
       myObjectMarshaller.marshal(myObject, outputStream);
       outputStream.flush();
       outputStream.close();When I view the XML payload of the request it looks like this:
    <?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>
    <ns2:myObject xmlns:ns2=\"http://sunconnection.sun.com/xml\">
       <myObjectId>0</myObjectId>
       <objectType>1</objectType>
       <description>Test Object</description>
    </ns2:myObject>As you can see the two XML representations of the object are identical except for the standalone attribute in the xml element.
    It'd be a hack to make the assumption that the standalone attribute will always be there in the marshalled object and to just hard code it into the XML string returned by my object to XML method. Since I'm using the same Marshaller to create the XML string as I am to perform the marshalling to the request I assume that there's some way to make it give the same XML in both cases, and that I'm doing something wrong in my method which converts the object to an XML string. If anyone can see where I'm going wrong in that method (myObjectToXmlString() above), or can suggest a better way of doing this, then I'll certainly appreciate the insight.
    --James                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    It turns out that I was taking the wrong approach in my object to XML string method. A cleaner/better way to do it, which gives the correct result, is this:
        private String myObjectToXmlString (final MyObject myObject)
            throws Exception {
            try {
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                myObjectMarshaller.marshal(myObject, stream);
                return stream.toString();
            } catch (Exception ex) {
                throw new Exception("Unable to convert a MyObject object to an XML String -- " + ex.toString(), ex);
        }--James                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • XML Datatypes in Oracle 9i

    My database architect would like to leverage the XML datatype support that is new in Oracle 9i. How can I configure TopLink to directly map object attributes to elements in an XML structure that is stored in an XML-type column?

    Marc,
    Yes. It is possible to map XMLType columns into your object model. It is accomplished using a direct-to-field mapping where the database column is an XMLType and the object model's attribute is a Document or String. In 9.0.3 of Oracle9iAS TopLink you must include the xdb.jar on your classpath, customize your configuration with an extended ConversionManager, and use a DescriptorEventListener.
    ConversionManager: Subclass the provided one and provide a conversion from XMLType to either the underlying DOM Document or XML representation of the string.
    DescriptorEventListener: Implement and register an event listener that will provide aboutToInsert and aboutToUpdate events for the class you are mapping the XML into. In these events you'll need to make use of the provided JDBC connection to convert the Document or String back into an XMLType object. (NOTE: If using Strings I believe you must use Oracle's XML parser to re-build the Document)
    A more detail technical tip will be availble soon and will be available through TopLink's OTN page (http://otn.oracle.com/products/ias/toplink/).
    Doug Clarke
    Product Manager
    Oracle9iAS TopLink

  • OInvoice Business Object XML Schema question

    I am trying to produce an xml file based on the oInvoices business object to use in an EDI translation.  I am running Sap Business One 2005 A SP:01 PL:03.  I used one of the sample programs in the SDK Samples folder to produce an XML schema of the oInvoices object.  The sample program is in the COM DI folder, program #06. ObjectSchemas.  When I run this program is produces an xml file that is really a schema for oInvoices, and it uses the GetBusinessObjectXmlSchema function for the oInvoices BoObjectType.  If I use the SaveXML function on the SAPbobsCOM.BoObjectTypes.oInvoices, I get a different xml file that does not use the same table or fields names.  (See sample below - schema uses the table name, OINV, SaveXml uses 'Documents' in place of the OINV name, schema has a QueryParams tag set, SaveXml does not, SaveXml has a Version defined within the AdminInfo, the Schema does not have this). Why doesn't the oInvoices xml schema match the xml file produced using the SaveXML function.  Which example below is the correct xml representation of an Invoice?  I have copied parts of each file below.
    oInvoices file produced using GetBusinessObjectXmlSchema for oInvoices:
    - <element name="BOM">
    - <complexType>
    - <all>
    - <element maxOccurs="1" minOccurs="0" name="BO">
    - <complexType>
    - <sequence>
    - <element maxOccurs="1" minOccurs="0" name="AdmInfo">
    - <complexType>
    - <all>
      <element maxOccurs="1" minOccurs="0" name="Object" type="long" />
      </all>
      </complexType>
      </element>
    - <element maxOccurs="1" minOccurs="0" name="QueryParams">
    - <complexType>
    - <all>
      <element maxOccurs="1" minOccurs="0" name="DocEntry" type="string" />
      </all>
      </complexType>
      </element>
    - <element maxOccurs="1" minOccurs="0" name="OINV">
    - <complexType>
    - <sequence>
    - <element maxOccurs="unbounded" minOccurs="0" name="row">
    - <complexType>
    - <all>
      <element maxOccurs="1" minOccurs="0" name="DocNum" type="long" />
      <element maxOccurs="1" minOccurs="0" name="DocType" type="string" />
      <element maxOccurs="1" minOccurs="0" name="Handwrtten" type="string" />
      <element maxOccurs="1" minOccurs="0" name="DocDate" type="string" />
      <element maxOccurs="1" minOccurs="0" name="DocDueDate" type="string" />
      <element maxOccurs="1" minOccurs="0" name="CardCode" type="string" />
      <element maxOccurs="1" minOccurs="0" ......
    OInvoices xml file produced using SaveXml
    - <BOM>
    - <BO>
    - <AdmInfo>
      <Object>13</Object>
      <Version>2</Version>
      </AdmInfo>
    - <Documents>
    - <row>
      <DocNum>5</DocNum>
      <DocType>dDocument_Items</DocType>
      <HandWritten>tNO</HandWritten>
      <Printed>tNO</Printed>
      <DocDate>20050116</DocDate>
      <DocDueDate>20050215</DocDueDate>
      <CardCode>C20000</CardCode>.....
    I did not copy all of the xml for each file as it would be too lengthy. 
    Thanks,
    Nancy Walk
    [email protected]

    Hi Nancy,
    I can´t find it right now, but I do remember reading that there were different XML definition versions for SBO objects. In the version 1, table names where used. In the version 2, object names where used. Looks like the schema defines version 2, but SBO is using version 2.
    I will check if I can found where I did read that. Try speaking with someone in SAP and about XML versions, perhaps they could help you with this info.
    Hope helps,
    Ibai Peñ

  • How to extract the actual XML document from soap message?

    My problem is " how to extract the actual XML document from soap message? "
    i just want to extract the attachment i.e. (pure XML document without any soap header or envolope).
    i could be ver thank full if u could solve my problem.
    [email protected]

    Hi,
    This is some skeleton code for extracting an attachment from a SOAPMessage.
    import javax.activation.DataHandler.;
    import javax.xml.soap.*;
    import javax.xml.message.*;
    Iterator allAttachments = message.getAttachments();
    AttachmentPart ap1 = null;
    while(allAttachments.hasNext()){
    ap1 = (AttachmentPart)allAttachments.next();
    //Check that the attachment is correct one. By looking at its mime headers
    //Convert the attachment part into its DOM representation:
    if(ap1.getContentType() == "text/xml"){
    //Use the activation dataHandler class to extract the content, then create a StreamSource from
    //the content.
    DataHandler attachmentContent = ap1.getDataHandler();
    StreamSource attachmentStream = new StreamSource(attachmentContent.getInputStream());
    DOMResult domAttachment = getDOMResult(attachmentStream);
    domAttachment holds an xml representation of the attachment.
    Hope this helps.

  • DB to XML mapping in DB Adapters

    Hi,
    I am evaluating DB Adapters. My Requirement is to get table rows as XML on which update/delete operations are being performed. XML gateway has a mechanism called db to xml mapping and an api is provided to retrieve the table row as xml by providing the transformation map code and primary key. Is there any such mechanism in DB adapters as well ? All i need is the xml representation of the table row after performing custom transformations. This capturing of xml should happen before any changes are commited to database (as i am intrested in capturing old .
    Pradeep

    Hi,
    I am evaluating DB Adapters. My Requirement is to get table rows as XML on which update/delete operations are being performed. XML gateway has a mechanism called db to xml mapping and an api is provided to retrieve the table row as xml by providing the transformation map code and primary key. Is there any such mechanism in DB adapters as well ? All i need is the xml representation of the table row after performing custom transformations. This capturing of xml should happen before any changes are commited to database (as i am intrested in capturing old .
    Pradeep

  • How do I marshall a list using javax.xml.bind.annotation?

    Hopefully this is so simple a cave man could do it.
    I had to remove the Duke Stars for the time being. I found another bug in the program that may have resulted in my array being empty.
    I'm trying to marshall a standalone document of my DeckImpl class. It is a deck of cards of course. It contains an array of CardImpl objects that need to be marshalled too. I could not figure out how to marhall the array so I have a marshall(Marshaller m) method that will
    initialize the List (see below) with an ArrayList. I figured the marshaller would do the rest but I just get the declaration and a closed <DECK />tag with the correct attributes (see way below) when I comment out the @XmlElementWrapper, or a DECK root node that simply contains a closed <CARDS /> tag with the line enabled. You can see tha CardImpl class is annotated too.
    I must be missing something obvious. Please help.
    @XmlRootElement(name = "DECK")
    @XmlType(name = "DECK")
    public class DeckImpl implements Comparable<DeckImpl> {
        @XmlAttribute
        public int id;
        @XmlAttribute
        public boolean isShuffled;
        @XmlAttribute
        public boolean isCut;
        public CardImpl[] cards;
        @XmlElementWrapper(name="CARDS")
        @XmlElements(@XmlElement(name="CARD",type=CardImpl.class))
        public List<CardImpl> CARDS;
        private static JAXBContext context;
        private static Marshaller marshaller;
    public DeckImpl(int id, boolean isCut, boolean isShuffled,
                CardImpl[] cards) {
            this.id = id;
            this.isShuffled = isShuffled;
            this.isCut = isCut;
            this.cards = cards;
            try {
                context = JAXBContext.newInstance(DeckImpl.class);
                marshaller = context.createMarshaller();
            } catch (JAXBException ex) {
                Logger.getLogger(CardImpl.class.getName()).log(Level.SEVERE, null, ex);
    //... class code goes here
    /** Generates XML representation of a deck
         * @param writer
         * @throws javax.xml.bind.JAXBException
        public void marshall(Writer writer) throws JAXBException {
            CARDS = new ArrayList<CardImpl>(cards.length);
            for (CardImpl i : cards) {
                CARDS.add(i);
            marshaller.marshal(this, writer);
    @XmlType(name = "CARD")
    public class CardImpl implements Comparable<CardImpl> {
        @XmlElement(name = "NAME")
        public String name;
        @XmlElement(name = "SUIT")
        public String suit;
        @XmlAttribute
        public int value;
        @XmlAttribute
        public int pointValue;
    //... class code
    }The output is:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?><DECK isCut="false" isShuffled="true" id="1"/>Regards,
    Bill
    Edited by: bthayer on Jan 24, 2009 7:15 AM
    Edited by: bthayer on Jan 25, 2009 7:02 AM

    There's a bit in here on marshalling.
    http://java.sun.com/webservices/docs/1.4/tutorial/doc/index.html
    Problem with JAXB (and I could be wrong - try posting on the Web Services / XML forum) is that you can only marshal the generated classes. This may mean that you need to create the object, and populate it using the setter / getter methods.
    Castor is much more friendly for this as it can marshall objects using reflections. You may also want to look into XMLBeans (which I have no exp of)

Maybe you are looking for

  • Header Text And Item Text in Sales Order

    Dear ALL First one: I have two different problems with text in sales order, when i create sales order after giving all the information like customer and material. If i navigate through the Go To-- > Header ---> Text then there is a dump is any idea w

  • No luck trying to capture vinyl albums

    I'm trying to figure out what I'm doing wrong when using Soundbooth to capture audio from vinyl albums. I'm using a turntable that's connected to a receiver. I've got RCA jacks connected to the receiver's tape playback plugs with the other end connec

  • Moving to the end of a result set

    When moving to the end of a result set using the keyboard shortcut Ctrl+End the view of the result moves to the last row, but the current field does not move. So when I use up or down keys after Ctrl-end, I'm back at the top of the result set. The cu

  • Problem with  monitor a job

    Hi all,    I am running a job which loads data from one DSO to another DSO . The update rules have a start routine which extract data from APO livecache using 2 -3 functional modules for some characteristics of the target DSO . Earlier this load was

  • Publishing AVI from Captivate 4 - why such a MASSIVE file size.

    I've produced the AVI from Captivate 4 without a problem, but the resulting file is massive; over 500 MG for a project with 47 slides. The .cp file for the project is only 7 MG.  Why is the AVI so massive?  Is there something in my setup causing it o