JAXB marshaling and unmarshaling

I used JAXB to generate nine classes (one is simply a type-safe enum) to correspond to my XML DTD. I then wrote the code to instantiate the root and some child elements which are all added to the root content. Then I am able to call validate() and marshal() on the root element and produce the desired XML. Great!
The trouble is that I'm having difficulty using these classes to unmarshal the XML that they validated and wrote. Has anyone else seen this? In some cases, the call to unmarshal() returns the root element with no content (e.g., "<myRoot/>"). In other cases, I get an InvalidContentException on a nested element that repeats (e.g., "Expected an end tag for a "fooList" element, but found a start tag for a "foo" element").
Has anyone else seen this? I've been through the bug parade and didn't catch this mentioned there.

Here's the code for the problem I'm running into. Is anyone able to reproduce the problem and diagnose it? I must be doing something wrong because the Checkbook example works just fine for me. Please help!
The obvious trouble here is that Test4.java does not correctly unmarshal the XML that it writes to temp.xml. Where have I gone wrong?
-------- begin cut (xyz.dtd) --------
<!ELEMENT Name ( #PCDATA ) >
<!ELEMENT Transaction ( Id, Name, Amt ) >
<!ELEMENT Transactions ( Transaction+ ) >
<!ATTLIST Transactions count NMTOKEN #IMPLIED >
--------- end cut (xyz.dtd) ---------
-------- begin cut (xyz.xjs) --------
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xml-java-binding-schema version="1.0-ea">
<options package="xyz"/>
<element name="Transactions" type="class" root="true">
<attribute name="count" convert="int"/>
<element-ref name="Transaction"/>
<element name="Name" type="value"/>
<element name="Amt" type="value" convert="int"/>
<element name="Id" type="value" convert="int"/>
<element name="Transaction" type="class">
<element-ref name="Id"/>
<element-ref name="Name"/>
<element-ref name="Amt"/>
--------- end cut (xyz.xjs) ---------
-------- begin cut (Test4.java) --------
import xyz.*;
import javax.xml.bind.*;
import javax.xml.marshal.*;
import java.io.*;
import java.util.Date;
import java.util.Random;
public class Test4 {
private static Random rand = new Random();
public static void main(String[] args) {
// need file to work with...
try {
File f = new File( "temp.xml" );
FileOutputStream fout =
new FileOutputStream( f );
// make some transactions
int TransCt = 1;
Transactions txns = new Transactions();
java.util.List transactions = txns.getTransaction();
for (int i=0; i < TransCt; i++) {
Transaction t = makeBogus();
transactions.add( t );
txns.setCount( TransCt );
txns.marshal( fout );
FileInputStream fin = new FileInputStream( f );
Transactions t = new Transactions();
t.unmarshal( fin );
t.marshal( System.out );
catch (Exception e) {
private static Transaction makeBogus() {
String[] names =
{ "Bob", "Larry", "Tom", "Ted", "Bill",
"Gail", "Louise", "Sam", "Erin", "Wilma" };
Transaction transaction = new Transaction();
// calculate transaction id...
int range = Integer.MAX_VALUE / 3 * 2;
int Id = rand.nextInt(range);
transaction.setId( Id );
// pick a name
transaction.setName( names[rand.nextInt(10)] );
transaction.setAmt( rand.nextInt( 100 ) );
return transaction;
--------- end cut (Test4.java) ---------

Similar Messages

  • JAXB marshal and unmarshal

    i have written some code to retrieve data from an XML file and mapped the data and display the mapped data in a new XML file, but i am able to display the mapped data in an MSdos window by running ANT, after this i am unable to write the displayed data in to XML file.
    Input XML file holds --- Firstname(Hello) and
    my MSdos display data ----------- Hello World
    is in this way
    I want the above out put in to XML file
    if any body know this help me.
    Thank you.

    IMHO these classes are not meant to be serialised, the XML produced is the medium that is tranmitted between programs. The XMLB classes are available at both ends to do the marshalling/unmarshalling.I dissagree, xml is just an interface to the outside world, so to speak. I'm working with a project that uses jini and rmi, I really don't need the extra hasle of writting custom serialization classes.

  • JAXB marshal "lt;" and "gt;" instead " " and " "... URGENT

    I defined in jaxb that some tag (un)marshal (from/to) org.w3c.dom.Document.
    But when jaxb marshalling, the assigned document has got
    "lt" instead "<"
    "gt" instead ">".
    This is "equals" characthers when is represent in browser, but itegrity of xml file in not same.
    How can I forced "<" and ">"?
    Please, can me anybody help?

    I assume you mean it displays the following substitutions in the output document.
    & lt;      <      less than
    & gt;      >      greater than
    & amp;      &      ampersand
    & apos;      '      apostrophe
    & quot;      "      quotation mark
    { I have had to add an artificial space after the & in the entity reference, to prevent this forum from doing the entity reference subsititution even!}
    These are predefined entity references, which are required for valid xml. Since xml element are delimited by '<' and '>', the parser needs to know that you are not trying to define new elements when you use these characters in element text.
    If you use a parser on the output xml, you will get '<' and '>' back as the resulting element text.

  • JAXB Marshalling

    jaxb marshalling for a xml file takes 8 secs in one system but it takes 1/2 min in another system for the same file. I want to know how to identifyu if there is any difference in the parsers being useed. I searched the Manifest files but unable to find reference to the parser being used. I even compared the version numbers of the API in the Manifest file and all the jars seem to be same version.
    Please help me in identifying what could be the problem.

    I don't know anything about either of the computers involved or the XML document involved, but I will take a guess and say there are differences in network access between the two computers.

  • JAXB Unmarshalling and namespace

    Hi All ,
    Im using jaxb to marshall and unmarshall xml messages.Every thing seems to work fine expect for one
    small part ...... the namespace is removed form the xml .For example
    <RECORD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Record.xsd">
    Any idea why this happens ?

    Hi Jimmy -
    Have you tried including this code at marshall time?
    marshaller.setProperty( Marshaller.JAXB_SCHEMA_LOCATION, "schema_path path_to_xsd.xsd");
    Good luck.

  • JAXB Marshalling devouring memory

    Hi there.
    I noticed some disturbing behavior with how JAXB marshals large XML documents. I have around 5000 data objects which, when marshalled, result in an XML document about 9.5 mb in size. Prior to calling marshal(), I had over 47mb available on my Heap. Before this method returned, an OutOfMemoryError had been thrown. I was able to fix this problem by setting my max Heap size to 128mb.
    My concern is how this will scale with larger data sets, as I don't want to keep throwing more and more ram at the problem. I haven't run any concrete benchmarks yet, but I was wondering if anyone has run into this problem before and could share some numbers with me.
    Thanks in advance!

    Immediately prior to calling marshal(), I have approx 47 mb available out of an original 64. So for 5000 catalog items, I'm using a max of 17 mb; that's 3.4 k for each item bound to JAXB. That's not unacceptable. The problem is that in the process of marshalling this data to XML, over 50 mb is being consumed. This XML is sent to a remote Web Service (the spec allows for xml up to 35mb), so the size of the document is not unreasonable.
    I did a little benchmarking, and found this behavior to scale fairly linearly, which is a Good Thing (128mb per 9000 items). However, I'm wondering if JAXB allows for more efficient memory management for marshalling larger data sets (i.e. Serializing binding objects to disk until it's time to build them to xml, or releasing objects as soon as they're marshalled).

  • Marshalling and Unmarshalling on xml

    is this the one of the way of parsing xml??

    If by "marshalling and Unmarshalling on xml" you mean converting between XML and Java, then yes, JAXB can be a viable alternative to SAX or DOM, depending on your requirements.
    It is a simpler solution if it's the binding that you actually need.
    If Java representation of XML isn't relevant and you're only concerned about firing events when a particular XML artifact is detected, then SAX would be more indicated.
    Take the good habit of listing your actual requirements before considering a range of options.

  • JAXB Marshalling of "double" problem - exponent is in the way

    An element declared as "xsd:double" in the schema is marshalled by JAXB as "3.000404E-4" to represent 0.0003000404 . When I try to process this XML document using XSLT, the standard number() function returns "NaN" because of the exponent in the representation of the number.
    Is there any way to have JAXB marshall this number in a way that is acceptable to XSLT?

    This seems to have a solution by using JAXB custom bindings. See http://forum.java.sun.com/thread.jsp?forum=34&thread=507037
    Thanks anyway.

  • Marshall and Re-Marshall in FML32 buffer

    Can anyone tell me how to Marshall and Re-marshall a structure in an FML32 buffer.
    Thanks in advance

    You can use tusc to show you the actual msgsnd/msgrcv system calls, so
    that you can see the actual message sizes. You will also be able to see
    the file I/O, if file transfer is being used.
    Tuxedo does not write to the ULOG every time it uses file transfer, just
    when it thinks it could have sent it as a message, but that fails for
    some reason.
    Fused() will show you the amount of data that will be transmitted. Add
    an extra 360 bytes for the Tuxedo header. If you are sending to a
    different machine type, the buffer will be encoded, and be much larger.
         Scott Orshan
    Per Lindström wrote:
    Hello everyone,
    I'm currently trying to figure out how to configure the [IPC] queues and kernel
    parameters regarding MSG* for a high-volume application. As one of the steps I'm
    trying to identify the size of the input message for a certain service. I know
    it's a rather big message, but I could use some more specific information.
    Using TMTRACE I get the impression that a certain message is 95960 bytes:
    TRACE:at: { tpservice({"MY_SERVICE", 0x0, 0x401a6278, 95960, 0, -1, {0, -2, -1}})
    and there's also a call to tptypes() (checking for FML32 buffer type) that's also
    returning 95960.
    However, if this message is larger than 64K (msgmax, msgmnb), wouldn't I be getting
    the fearsome message "will try file transfer" in the ULOG?
    My question is if what TMTRACE shows is the size AFTER re-indexing of the FML32
    buffer, and, in that case, if there is any way of seeing the "transmitted size"
    (which I believe is unindexed) of the message? There are some ia trace messages
    regarding tpalloc() of rpcrqst buffers - are they of any use in this situation?
    This is running Tuxedo 6.5 on HP-UX 11.00.
    Any input on this welcome!
    Best regards,

  • JAXB, Castor and extending behaviour

    I need to do XML data binding and have been evaluating Castor and JAXB. One of the main differences seems to be Castor is class based while JAXB is interface based.
    The ability to generate classes to marshal, unmarshal, and validate is really great but a schema can't define all the behaviour your class may want to have.
    Given that the auto-generated classes dont have all the methods I need what do I do? Well in Castor its easy, I just subclass the auto-generated classes and add the behaviour as required. It works well. How can I do a similar thing in JAXB? Extending the interface isnt enough because you need to extend a class to implement the new interface However, in JAXB the implementation class is not supposed to be used directly by the application.
    Can anyone suggest the best way to solve this problem?

    One thing I am doing now is generating all the classes initially using the default behaviour. Then I take the one of the generated classes and modify it. Then I create an entry in the binding file specifying the class as the impl class for that node. You can then rerun the generator and it will not write over the class you have changed. I don't see why you couldn't just extend the class and set the extended class name in the binding file. That's actually better than what I've got now because I can keep my methods separate from the generated class and it's easier to regenerate that class too.
    My question is whether there is a way to get JAXB to create bound properties the way that you can with Castor?

  • Java 6, JAXB 2 and X3D (version 3.0)

    Hi everyone,
    I'm trying to unmarshall a X3D file using JAXB2 included in Java 6. I successfully generated the classes from the schema (http://www.web3d.org/specifications/x3d-3.0.xsd). I then created a simple X3D file using Blender and the Duke model available at https://duke.dev.java.net/models/Duke.lwo.
    However, when I try to unmarshall the model I get an exception. The X3D-file validates correctly using the validator in IntelliJ IDEA, but JAXB seems to fail somehow.
    The code used for unmarshalling:
    public static X3D loadModel(File input) {
        X3D model = null;
        try {
            JAXBContext context = JAXBContext.newInstance();
            Unmarshaller unmarshaller = context.createUnmarshaller();
            unmarshaller.setEventHandler(new javax.xml.bind.helpers.DefaultValidationEventHandler());
            model = (X3D) unmarshaller.unmarshal(input);
        } catch (Exception e) {
            e.printStackTrace();  // TODO Fix exception handling.
        return model;
    }The Exception I get is:
    DefaultValidationEventHandler: [FATAL_ERROR]: unexpected element (uri:"", local:"X3D"). Expected elements are (none)
    Location: line 4 of file:/C:/Projects/JFokus/jfokus-demos/jogl-presentation/Duke.x3d
    javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"X3D"). Expected elements are (none)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:523)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:199)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:194)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:71)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:920)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:366)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:347)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:101)
         at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:501)
         at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:767)
         at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:400)
         at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:626)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3084)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:912)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:645)
         at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
         at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:508)
         at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:807)
         at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
         at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:107)
         at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
         at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:194)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:167)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:151)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:169)
         at se.jsolutions.jogl.X3dModel.loadModel(X3dModel.java:27)
         at se.jsolutions.jogl.X3dModel.main(X3dModel.java:37)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:597)
         at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)
    Tried with other X3D-models I found online, with the same result. Any suggestions or help would be greatly appreciated.
    // Erik

    public static X3D loadModel(File input) {
       X3D model = null;
       try {
          JAXBContext context = JAXBContext.newInstance(model.getPackage().getName());
          Unmarshaller unmarshaller = context.createUnmarshaller();
          model = (X3D) unmarshaller.unmarshal(input);
       } catch (Exception e) {
          e.printStackTrace();  // TODO Fix exception handling.
       return model;

  • JAXB Marshalling Question

    below is what I get for marshalling some JAXB generated class instance, and i notice that several namespace was create ns1, ns2, ns3.... which are actually all sharing the same namespace, is there anyway (any option) that I can set to optimize it, so they can all simply use ns1, and won't define ns2, ns3...
    thank you.
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <aaa xmlns="http://schema.abc.com/def/gh">
    <ns1:HeaderReq xmlns:ns1="http://schema.abc.com/def">
    <ns2:ccc xmlns:ns2="http://schema.abc.com/def">accountToken</ns2:ccc>
    <ns3:firstName xmlns:ns3="http://schema.abc.com/def">Jacob</ns3:firstName>
    <ns4:lastName xmlns:ns4="http://schema.abc.com/def">Tseng</ns4:lastName>

    Hi Jacob,
    Here is the solution I used for getting rid of ns1,ns2 etc..when I was getting ns1,ns2.. etc.along with http://www.xyz.com/xml/yourxml in the generated XML output
    It worked for me. Let me know if you need any further help.
    Please include the Following Code when you are marshalling the Document
    ======================== Your Main Java File ======================
    try {
              m.setProperty("com.sun.xml.bind.namespacePrefixMapper",new NamespacePrefixMapperImpl());
    // m is the Marshaller Object
    // NamespacePrefixMapperImpl()
    // You have to implement, sample code is given below
         catch ( PropertyException pe)
              System.out.println("Property Exception : " + pe.toString());
    Here is the Sample Code to implement NamespacePrefixMapperImpl()
    import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
    class NamespacePrefixMapperImpl extends NamespacePrefixMapper {
    public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) {
    // W3c to show a prefix "xsi"
    if( "http://www.w3.org/2001/XMLSchema-instance".equals(namespaceUri) )
    return "xsi";
    // Your namespace http://www.xyz.com/yourxml/ to show prefix "tns"
    if( "http://www.xyz.com/yourxml/".equals(namespaceUri) )
    return "tns";
    return suggestion;

  • JAXB - Marshalling populated Java object into XML

    I have a populated Java object that I'd like to marshall to an xml file.
    I don't instantiate this object from a DTD, nor do I need to generate the object via unmarshalling an xml. I'm just trying to build something akin to a toXML() method for this object.
    Is JAXB what I should be using?
    Any suggestions?
    Thanks a lot.

    Hi Paul,
    Did you ever sort this out?
    I too am now having problems with Marshalling to and from XML.
    I have been able to write my own Marshalling class but can't seem to be able to DeMarshal a XML stream to a SOAP object.
    Please reply to this message if you are able to maybe shed some light on my problem.
    I have a populated Java object that I'd like to
    marshall to an xml file.
    I don't instantiate this object from a DTD, nor do I
    need to generate the object via unmarshalling an xml.
    I'm just trying to build something akin to a toXML()
    method for this object.
    Is JAXB what I should be using?
    Any suggestions?
    Thanks a lot.

  • JAXBContext and unmarshaling xml document to a class that came from a jar.

    I'm trying to unmarshal, code:
                   try {
                        JAXBContext jc = JAXBContext.newInstance(clazz);
                        Unmarshaller m = jc.createUnmarshaller();
                        Document doc = XmlUtils.createDom(body);
                        javax.xml.bind.JAXBElement<T> res = (javax.xml.bind.JAXBElement<T>)m.unmarshal(doc);
                        return res.getValue();
                   } catch (JAXBException e) {
    now i have an ObjectFactory inside the jar that resolve (xmlRegistry) the correct type.
    but the @XmlAccessorType(XmlAccessType.FIELD) binding is not working while the class is comming from a jar.
    when i 'Link source' to my project is working fine.
    I guess it has something to do with reflection.
    the class which i want to unmarshal to looks like this:
    @XmlType(name = "GetSessionIDResponseType", propOrder = {
    public class GetSessionIDResponseType
    extends AbstractResponseType
    implements Serializable
    private final static long serialVersionUID = 12343L;
    @XmlElement(name = "SessionID")
    protected String sessionID;
    * Gets the value of the sessionID property.
    * @return
    * possible object is
    * {@link String }
    public String getSessionID() {
    return sessionID;
    * Sets the value of the sessionID property.
    * @param value
    * allowed object is
    * {@link String }
    public void setSessionID(String value) {
    this.sessionID = value;
    not the field as u can see is protected though it has getter and setter.
    anyway i must get the link source project to a jar and i cant do that cause the unmarshal is basically failing.
    any idea?
    Edited by: 813927 on Nov 20, 2010 6:10 AM

    I've overcome the problem by adding the unmarsheling code inside the jar.
    though i dont the problem i tried to set the fields to be public and it didnt work.
    very strange so far.

  • Marshaling and xml generation

    Can any one pls tell for generating an xml file from fetching data from database do i have to use marshalling.
    Why exactly marshalling is being used.?How is DomBuilder useful and diferent from marshaller?

    Thanks for ur reply.
    Let me make myself clear ...
    I have to generate a flat xml file by pulling the data from db.
    Now i want to use a dom builder where as one if my collegue who is fresher wants to use castor's marshalling process to generate xml.
    I know the concept of marshalling which is used for serilaizing the object graph so that it is unmarshalled on the other end.But iam unable to convince her.
    It would be great if u can give me 2 lines answer which is convincing enough to make her understand.

Maybe you are looking for