Marshalling Java to XML using JAXB

Hi,
I have just downloaded the JAXB reference implementation and have been trying out marshalling Java objects to XML.
I have a very basic question - can I convert the data from my Java classes into XML and simply send it as a String to another object instead of only having to write it out into a File? Ideally, I want to convert Java to XML from my Business Layer and send XML to my Presentation Layer objects. To do this, I need the XML returned to me in the form of a String and not a File. Any tips will be highly appreciated.

You should be using Object Factory. JAXB provides one ObjectFactory for each schema.
Create that particular object and after filling values into that object please set it to the Jaxb object where ever it fits.
Like
<Message>
<Type></Type>
<Name></name>
<Message>
If you want to set Name then JAXB will provide you with setter which be used to set or get. Util you are setting an object which is can repeat more that once then you will have to get a list from the JAXB object and add those objects into the list which will automatically add it the main object.

Similar Messages

  • Error when reading data from XML using JAXB?

    Hi all,
    I get the error message when reading data from XML using JAXB.
    [org.xml.sax.SAXParseException: The entity name must immediately follow the '&' in the entity reference.]
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException
    (AbstractUnmarshallerImpl.java:315)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:481)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:199)
         at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:168)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
         at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    I don't find the reason, please help!
    Thanks in advance!

    The problem is sovled.

  • Parsing ejb-jar.xml using jaxb

    hi all,
    how to parse the ejb-jar.xml using jaxb? can anybody send the information about the API which we have to use to parse the ejb-jar.xml? (ejb2.0)
    i need the details about all ejbs in an application, (like jndi name, Home and Remote name). so, how can i parse the ejb descriptors?
    regards,
    panneer

    Hi Panneer,
    Well, parsing the EJB descriptors is, in principle, a task for the EJB container where they are deployed. From what you wrote I assume that you need to gather that kind of info to visualize in some (monitoring?) tool. Is that correct?
    If so, the question would be whether you have access to the EJB jar on the file system (before it's deployed) or you can only connect to the server with the already deployed EJBs. In the latter case, this information is shown in the [NWA plugins|http://help.sap.com/saphelp_nwce10/helpdata/en/0b/5b5a42ea221153e10000000a155106/frameset.htm]. There are also some [telnet commands|http://help.sap.com/saphelp_nw04/helpdata/en/79/3cf82ade038d45a21fbfdaee349b22/frameset.htm] in NW 04 and 7.0 (04s).
    If you have access to the EJB jar file, you can parse the descriptors using DOM or SAX, but I'm not aware of any pre-defined JAXB API for this purpose. Probably you can also generate the mapped classes yourself and use them, however I'm not sure how that works with DTD (because of EJB 2.0).
    HTH!
    \-- Vladimir

  • Entity include with relative path in XML using JAXB

    Moving this from the Java Technologies for Web Services forum to this one.
    With the jwsdp jars I'm trying to use JAXB to load in several specified XML files. This works fine. The XML files are read in from a relative link "/templates/mainXML.xml" and the xml string read in and passed to the unmarshaller as a StreamSource:
    BufferedReader reader = new BufferedReader(new InputStreamReader(getClass().getResource(xmlPath_).openStream()));
    while ( (line = reader.readLine()) != null) {
    buff.append(line.trim()+"\n");
    String xml = buff.toString();
    u.unmarshall(new StreamSource(new StringReader(xml)))
    But my XML files are becoming rather large with some repitition across the files so I'd like to use the entity incude in the header of the XML to abstract some of the XML into addMe.xml e.g:
    <!DOCTYPE StrategyTemplate [
    <!ENTITY IncludeTimeComponent SYSTEM "file:///templates/addMe.xml">]>
    with &IncludeTimeComponent;
    But it gives this error:
    Caused by: java.io.FileNotFoundException: \templates\addMe.xml (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:106)
    at java.io.FileInputStream.<init>(FileInputStream.java:66)
    at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:70)
    at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:161)
    at java.net.URL.openStream(URL.java:1007)
    at weblogic.apache.xerces.impl.XMLEntityManager.startEntity(XMLEntityManager.java:836)
    at weblogic.apache.xerces.impl.XMLEntityManager.startEntity(XMLEntityManager.java:767)
    at weblogic.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanEntityReference(XMLDocumentFragmentScannerImpl.java:1095)
    at weblogic.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(XMLDocumentFragmentScannerImpl.java:1513)
    at weblogic.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:329)
    at weblogic.apache.xerces.parsers.DTDConfiguration.parse(DTDConfiguration.java:525)
    at weblogic.apache.xerces.parsers.DTDConfiguration.parse(DTDConfiguration.java:581)
    at weblogic.apache.xerces.parsers.XMLParser.parse(XMLParser.java:152)
    at weblogic.apache.xerces.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1175)
    at weblogic.xml.jaxp.WebLogicXMLReader.parse(WebLogicXMLReader.java:135)
    at weblogic.xml.jaxp.RegistryXMLReader.parse(RegistryXMLReader.java:152)
    at com.lb.cmte.oms.interpreter.jaxb.impl.runtime.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:140)
    ... 11 more
    It works fine if I put the file in the working directory or supply the full path e.g.
    <!DOCTYPE StrategyTemplate [
    <!ENTITY IncludeTimeComponent SYSTEM "file:///C:/dev/templates/addMe.xml">]>
    with &IncludeTimeComponent;
    I've tried using jwsdp2.0 jars rather than 1.4 I was using previously, but with the same result.
    But I don't want to do that, because I don't know where that might be. I'd like to be able to supply the xml file's path as it would be shown within a JAR as I do currently for the mainXML.xml files. Thanks in advance for any help!

    Oh, I see why. When XML talks about a "relative path" that means relative to the URL the XML was loaded from. But when the parser doesn't have such a URL -- for example in cases like yours where you are parsing from a String -- then it falls back to assuming the XML was loaded from the current working directory.
    This is almost never a good assumption, but what else can it do?
    Looking at your code, I don't understand why you are parsing from a String anyway. All of that code that reads from an input stream, ignoring the line endings and putting back new line endings, seems pointless to me. You should just marshal directly from getClass().getResource(xmlPath_) as far as I can see. Then your relative paths would work just fine.

  • Problem in Marshaling UnMarshaling with @XmlAnyElement using JAXB

    Hi all,
    I am having a class annotated with XML binding annotations. I am using this class to marshal and unmarshal XML content.
    I am having one class named Data. This class is field of some other class.
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlType(name = "", propOrder = {
        "any"
    @XmlRootElement(name = "Data")
    public class Data {
        @XmlAnyElement
        protected Element any;
        public Element getAny() {
            return any;
        public void setAny(Element value) {
            this.any = value;
    Data class is having one element named any. any holds any kind of XML Content.
    Now when I Unmarshal XML content to java class displayed above it works fine.
    But when Marshaling java class to XML it adds some unwanted namespaces and prefixes to content in any element in Data class.
    I am using javax.xml.bind.JAXBContext class for getting javax.xml.bind.Marshaller and javax.xml.bind.Unmarshaller.
    Here are the XML Data:
    Original:
    <bh:BookRequest xmlns:bh="http://www.mybookstore.com">
         <bh:Data>
              <Books xmlns="http://www.anynamespace.com">
                   <Book>
                        <Name>Any Java Book1</Name>
                        <Price>$5.0</Price>
                        <Publication>Any Publication</Publication>
                   </Book>
                   <Book>
                        <Name>Any Java Book2</Name>
                        <Price>$7.0</Price>
                        <Publication>Any Publication2</Publication>
                   </Book>
                   <Book>
                        <Name>Any Java Book3</Name>
                        <Price>$6.5</Price>
                        <Publication>Any Publication3</Publication>
                   </Book>
              </Books>
         </bh:Data>
    </bh:BookRequest>After Marshaling and Unmarshaling:
    <bh:BookRequest xmlns:bh="http://www.mybookstore.com">
         <bh:Data>
              <Books:Books xmlns:Books="http://www.mybookstore.com" xmlns="http://www.anynamespace.com">
                   <Book>
                        <Name>Any Java Book1</Name>
                        <Price>$5.0</Price>
                        <Publication>Any Publication</Publication>
                   </Book>
                   <Book>
                        <Name>Any Java Book2</Name>
                        <Price>$7.0</Price>
                        <Publication>Any Publication2</Publication>
                   </Book>
                   <Book>
                        <Name>Any Java Book3</Name>
                        <Price>$6.5</Price>
                        <Publication>Any Publication3</Publication>
                   </Book>
              </Books:Books>
         </bh:Data>
    </bh:BookRequest>Notice the <Books> element in both XML above.
    First one is the actual content. Second one is the Marshalled XML with addtional Namespace and prefixes.
    I don't want this behaviour. *I want Marshaling and UnMarshaling not to touch Content in any element of Data Class.I want that content as it is.* Is there any way to do so?
    Any comment for this will help me.
    thanks in adavnce,
    TYPurohit.

    What exactly the message mean: Use the "-extension" switch.
    My work around is to remove the abstract="true" from abstract element. Is there a better way?
    thanks.

  • Problem unmarshalling xml using JAXB

    I am using JAXB for processing xml, which comes from an external source. Most often, the xml gets changed from external source which causes the error during unmarshalling as the xsd has not changed. Is there a way to process the xml in same way even if xsd hasn't changed, like converting new xml to one as per xsd etc. Someone has mentioned using xslt, but I would like to get more ideas on any other technologies or third party tools to overcome this issue so that I do not have to reply upon changing xsd everytime. Thanks

    Most often, the xml gets changed from external source which causes the error during unmarshalling as the xsd has not changed.So, you've got garbage input. Your goal should be to stop that from happening rather than trying to make it work.
    so that I do not have to reply upon changing xsd everytimeIf you have to keep changing the schema then perhaps JAXB wasn't a suitable technology choice here. Or maybe the design wasn't done properly. Or maybe (see earlier comment) the input files aren't being produced properly. At any rate you need to fix the underlying problem before writing code.

  • Appending Data in XML File using JAXB

    I need to write the 50,000 records into XML file. But at a time i need to write only 1000 records into XML. How do i append the data into XML using JAXB.

    I have tried but the data is written in the following way:
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Users xmlns="http://www.yyyy.com/umc/importer/jaxb">
    <User id="101" xmlns="">
    <username>gjhs</username>
    <password>hdfhhdf</password>
    <role>df</role>
    <email>sdd</email>
    <phone>sdfdf</phone>
    <description>shkl</description>
    <property name="ernnker" value="hkdfhk"/>
    </User>
    </Users>
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Users xmlns="http://www.yyyy.com/umc/importer/jaxb">
    <User id="101" xmlns="">
    <username>gjhs</username>
    <password>hdfhhdf</password>
    <role>df</role>
    <email>sdd</email>
    <phone>sdfdf</phone>
    <description>shkl</description>
    <property name="ernnker" value="hkdfhk"/>
    </User>
    </Users>
    If i can eliminate the following lines from the above files then my job is done:
    </Users>
    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <Users xmlns="http://www.yyyy.com/umc/importer/jaxb">

  • Query in Unmarshaling using JAXB

    Hi,
    I have some chinese characters in my xml. When i try to read those string from XML using JAXB Unmarshaling and print the same, it is getting changed to some unicode character.
    Help me in this regard.
    As the chinese characaters are getting changed after preview, if u can contact my thro mail, it will be better ([email protected] is my email id)
    Regards
    Ravishankar

    Please post the error message and the exception stack.
    My guess is that the error is: your VO's SQL statement did not include the primary key attribute (say Empno).
    Thanks.
    Sung

  • Java Mapping Using JAXB [Java Arch for XML Binding]

    Hi All,
    Anyone tried using JAXB  [Java Architecture for XML Binding API available with Java WebServices Pack] technique for XML processing in Java Mapping??
    I am facing the following problems..
    1. I am not able to generate namespace while marshalling target XML [In standalone mode and not tried in XI].
    2. What are the jar files we need to import?
       I tried importing the following jar files in XI.
    jaxb-api.jar,jaxb-impl.jar,jaxb-libs.jar,jax-qname.jar,namespace.jar,relaxngDatatype.jar
      and getting some errors while importing these files in XI.
    3. It throws error at runtime [Interface Mapping-Test Tab]
       like Resource not found:javax/xml/bind/Messages_en.properties,javax/xml/bind/Messages_en_US.properties
    4. Even after creating a copy of available file Messages.Properties with name: Messages_en.properties and Messages_en_US.properties.. it is not generating any messages in Target message tab
    Thanks in Advance,
    Ananth Chinnaraj

    Sravya ,
    I have searched wide and far for this, but no success.
    A lot on JAXB XI and Webdynpro, but nothing on JAXB, XI and mappings.
    Could you please post the url here ?
    Thanks and kind regards,
    Jan

  • Marshaling problem in creation of xml thru JAXB

    Hi java gurus,
    I am trying to create an XML which will has the data of database using JAXB. I am able to generate JAXB classes, but its giving some error the stack trace is like this
    java.lang.NoSuchMethodError: com.sun.xml.bind.marshaller.XMLWriter.setXmlDecl(Z)V
         at org.bas.dss.common.vo.bii.impl.runtime.MarshallerImpl.createWriter(MarshallerImpl.java:223)
         at org.bas.dss.common.vo.bii.impl.runtime.MarshallerImpl.createWriter(MarshallerImpl.java:238)
         at org.bas.dss.common.vo.bii.impl.runtime.MarshallerImpl.createWriter(MarshallerImpl.java:233)
         at org.bas.dss.common.vo.bii.impl.runtime.MarshallerImpl.marshal(MarshallerImpl.java:126)
         at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:66)
         at org.bas.dss.common.dao.MetaDAO.createInstInformation(MetaDAO.java:627)
         at org.bas.core.fidownload.DownloadActionHandler.getInstInfoXMLData(DownloadActionHandler.java:163)
         at org.bas.core.fidownload.DownloadActionHandler.performPreDownloadAction(DownloadActionHandler.java:74)
         at org.bas.core.fidownload.DownloadAction.perform(DownloadAction.java:129)
         at org.bas.core.fidownload.DownloadAction.execute(DownloadAction.java:79)
    the method is like this,
    valueObject = getInstInformation (registrationId, appVersionId);
    System.out.println("MetaDAO-->valueObject:"+valueObject); //here i am gettingthe object
    context = JAXBContext.newInstance("org.bas.dss.common.vo.bii");
    System.out.println("MetaDAO-->context:"+context); //here i am getting the context
    sumissionInfoMarshaller = context.createMarshaller();
    System.out.println("MetaDAO-->sumissionInfoMarshaller:"+sumissionInfoMarshaller); //here also i am getting some object type
    sumissionInfoMarshaller.setProperty(
    Marshaller.JAXB_FORMATTED_OUTPUT,Boolean.TRUE);
    System.out.println("MetaDAO-->MetaDAO-->");
    sumissionInfoMarshaller.marshal (valueObject, streamToWrite); // the problem is coming here.
    anyone can suggest what will be the problem, and tell me how can i resolve this issue,
    thanks in advance,
    varma

    Pl post this question to SDK Forum

  • Creating a Java content tree from scratch and then marshal it to XML data

    Hi,
    After binding a schema using JAXB binding, I wrote a class to create a Java content tree from scratch and then marshal it to create an XML document. To see if the resulting xml document is correct, I opened it in XMLSpy and tried to validate it against the original schema.... I got the following error:
    "Unable to locate a reference to a supported schema kind (DTD, DCD, W3C Schema, XML-Data, Biz Talk) within this document instance"
    Then I realized that the generated xml document didnot contain the following for the root element:
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" and xsi:schemaLocation="....."
    i.e, the XML Schema Instance namespace and the schema location.
    How do I get these attributes incorporated into the XML document generated during the marshal process.
    Thanks.

    How do I get these attributes incorporated into the XML document generated during the marshal process.
    Add xmlns:xsi and xsi:schemaLocation attributes to the root element in the schema.
    <xsd:attribute name="xmlns:xsi"  fixed="http://www.w3.org/2001/XMLSchema-instance"/>

  • JAXB 1: is it possible to go from enum simulation in Java to XML Schema?

    I know how to get an enum simulation in java from XML schema, but can it be done in the other direction, in the context of a web service implementation?
    The thing is from schema to java a customization file is used. But there's no specification for such a customization file usability when going from java to schema. So far, i'm getting a string for enum wrapper.

    Well, i got it to work in JAXB 1, w/o xfire, schema-to-java. Marshall and unmarshall.
    But w/ xfire, it doesn't appear to be possible. Would probably require implementing it for them myself...

  • Help in Java XML Binding (JAXB)

    Looking for a JAVA written program that will provide interface to complex XML files using JAXB.
    Requirement : JAVA progam will report on existing XML using a simple GUI that will run on Windows. Program should be able to be emailed and installed with all components including XML files and schema. Purpose of this program is twofold.

    Sir,
    It is bad to expect people to solve assignments for you. Would you elaborate on where you are stuck?

  • Binding XML to java types generated using Oracle Class Gen

    Hi,
    how can you bind an XML to the java types generated using the class gen provided byOracle.
    I am using oracle 9i production. as part of my design, i have to read an xml input in my java class and use the contents to create some records and send a response xml back.
    The latter part of i can do as the java types provide setter methods to set the data and conversion to xml.
    Jaxb can be using to bind xml to java datatypes but its not supported in Oracle9i.
    What are the alternatives for achieving the same?
    Thanks
    Ashwin

    Hi Ashwin,
    This is a bit outside my area of expertise, but I did run an older version of TopLink in the Oracle database java VM a few years back so I'll base my advice on that. Hopefully other forum members can correct me if I steer you wrong.
    First you will need to set up your XML environment:
    I believe the Oracle 9i database includes a JDK 1.3 VM. You will first need to determine if the VM includes any JAXP APIs. I believe there is an SQL query that allows you to query the classes available in the VM. First check if javax.xml.parsers.DocumentBuilderFactory is present.
    If the JAXP APIs are already present in the database you will need to do the following. First load the class javax.xml.namespace.QName into the database. You can extract this from xmlparserv2.jar or from Suns Java Web Service Developer Pack jax-qname.jar. Then you will need to load the JAXB APIs. You can load xml.jar or jaxb-api.jar from Sun's JWSDP.
    If the JAXP APIs are not present you will need to load the 10.1.3 version of the XDK jars (these are shipped with the 10.1.3 TopLink install). Load xmlparserv2.jar and xml.jar into the database.
    Second you will need to setup your TopLink environment:
    Load toplink.jar into the database. If the JAXP APIs were already present and you didn't load the 10.1.3 XDK jars into the database you will need to set the following System property.
    toplink.xml.platform=oracle.toplink.platform.xml.jaxp.JAXPPlatform-Blaise

  • How to read the attribute of the xml file using jaxb

    Thanks,
    Buddy as i have a issue i have to read the xml file using jaxb and xml file contains this data and i have read the attribute like name , desc and action for a particular menu name pls tell the code how to do this it will be a great favour to me
    thanx in advance
    Rasool
    <contextmenu>
    <menu name='Lead' >
    <menuitem name='newlead' desc='New Lead' action='/leads.do?dispatch=insert' />
    <menuitem name='editlead' desc='Edit Lead' action='' />
    <menuitem name='leadinfo' desc='Lead Information' action='' />
    </menu>
    <menu name='Cases' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    <menu name='Contact' >
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    <menuitem name='' desc='' action='' />
    </menu>
    </contextmenu>

    What my program do is to get the encoding of XML files and convert them to UTF-8 encoding files, while I need this "encoding" information of the original XML document thus I can convert...
    After reading specifications and JDOM docs, the truth turns to be disappointed, no function is provided to get this information in JDOM level 2(the current released one), while it's promissed that this function will be provided in JDOM level API....
    Thanx all for your help and attention!!!

Maybe you are looking for