Generating an XML Document with JAXB
by Deepak Vohra12/15/2004
An XML Schema represents the structure of an XML document in XML syntax. J2EE developers may require an XML document to conform to an XML Schema. The Java Architecture for XML Binding (JAXB) provides a binding compiler, xjc, to generate Java classes from an XML Schema. The Java classes generated with the JAXB xjc utility represent the different elements and complexTypes in an XML Schema. (A complexType provides for constraining an element by specifying the attributes and elements in an element.) An XML document that conforms to the XML Schema may be constructed from the Java classes.
In this tutorial, JAXB is used to generate Java classes from an XML Schema. An example XML document shall be created from the Java classes. This article is structured into the following sections.
- Preliminary Setup
- Overview
- Generating Java Classes from XML Schema
- Creating an XML Document from Java Classes
Preliminary Setup
To generate Java classes from an XML Schema with the JAXB, the JAXB API classes and the xjc utility are required in the CLASSPATH variable. Install the Java Web Service Developer Pack (JWSDP) 1.5 to a installation directory. Add the following .jar files to the CLASSPATH variable.
<JWSDP>/jaxb/lib/jaxb-api.jar<JWSDP>/jaxb/lib/jaxb-impl.jar<JWSDP>/jaxb/lib/jaxb-libs.jar<JWSDP>/jaxb/lib/jaxb-xjc.jar<JWSDP>/jwsdp-shared/lib/namespace.jar<JWSDP>/jwsdp-shared/lib/jax-qname.jar<JWSDP>/jwsdp-shared/lib/relaxngDatatype.jar
<JWSDP> is the directory in which Java Web Service Developer Pack 1.5 is installed. Add <JWSDP>/jaxb/bin to the PATH variable. The <JWSDP>/jaxb/bin directory contains the xjc compiler. Add the <JWSDP>/jwsdp-shared/bin directory to the PATH variable. The <JWSDP>/jwsdp-shared/bin directory contains the setenv batch file to set the environment variables JAVA_HOME, ANT_HOME, and JWSDP_HOME.
Overview
JAXB generates Java classes and interfaces corresponding to the top-level elements and top-level complexType elements. In a XML Schema, an element is represented with <xs:element/>, and a complexType is represented with <xs:complexType/>. In this tutorial, an example schema that represents articles published in a scientific journal is compiled with the JAXB binding compiler. This schema has top-level element and complexType declarations. The example XML Schema, catalog.xsd, is below.
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<xsd:element name="catalog" type="catalogType"/>
<xsd:complexType name="catalogType">
<xsd:sequence>
<xsd:element ref="journal" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
<xsd:attribute name="section" type="xsd:string"/>
<xsd:attribute name="publisher" type="xsd:string"/>
</xsd:complexType>
<xsd:element name="journal" type="journalType"/>
<xsd:complexType name="journalType">
<xsd:sequence>
<xsd:element ref="article" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:element name="article" type="articleType"/>
<xsd:complexType name="articleType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="author" type="xsd:string"/>
</xsd:sequence>
<xsd:attribute name="level" type="xsd:string"/>
<xsd:attribute name="date" type="xsd:string"/>
</xsd:complexType>
</xsd:schema>
Some of the XML Schema constructs are not supported by JAXB. If such unsupported constructs are included in a schema, an error will be generated when you try to generate Java classes from them with xjc. The following schema elements are not supported: xs:any, xs:anyAttribute, xs:notation, xs:redefine, xs:key, xs:keyref, and xs:unique. The following schema attributes are not supported: complexType.abstract, element.abstract, element.substitutionGroup, xsi:type, complexType.block, complexType.final, element.block, element.final, schema.blockDefault, and schema.finalDefault.
Generating Java Classes
The xjc utility is run on the schema to bind a schema to Java classes. Run the xjc utility on the example schema with the command:
>xjc catalog.xsd
Some of the options for the xjc command-line interface are listed in the table:
-nv | Strict validation of the input schema(s) is not performed. |
-b <file> | Specifies the external binding file. |
-d <dir> | Specifies the directory for generated files. |
-p <pkg> | Specifies the target package. |
-classpath <arg> | Specifies classpath. |
-use-runtime <pkg> | The impl.runtime package does not get generated. |
-xmlschema | The input schema is a W3C XML Schema (default). |
For the example schema catalog.xsd, xjc generates 45 classes, as shown by xjc's output below:
parsing a schema...
compiling a schema...
generated\impl\runtime\ErrorHandlerAdaptor.java
generated\impl\runtime\MSVValidator.java
generated\impl\runtime\NamespaceContext2.java
generated\impl\runtime\UnmarshallableObject.java
generated\impl\runtime\MarshallerImpl.java
generated\impl\runtime\ValidationContext.java
generated\impl\runtime\UnmarshallerImpl.java
generated\impl\runtime\DefaultJAXBContextImpl.java
generated\impl\runtime\ContentHandlerAdaptor.java
generated\impl\runtime\GrammarInfoFacade.java
generated\impl\runtime\UnmarshallingContext.java
generated\impl\runtime\UnmarshallingEventHandlerAdaptor.java
generated\impl\runtime\XMLSerializable.java
generated\impl\runtime\Discarder.java
generated\impl\runtime\PrefixCallback.java
generated\impl\runtime\SAXMarshaller.java
generated\impl\runtime\NamespaceContextImpl.java
generated\impl\runtime\UnmarshallingEventHandler.java
generated\impl\runtime\GrammarInfo.java
generated\impl\runtime\InterningUnmarshallerHandler.java
generated\impl\runtime\ValidatableObject.java
generated\impl\runtime\GrammarInfoImpl.java
generated\impl\runtime\ValidatingUnmarshaller.java
generated\impl\runtime\ValidatorImpl.java
generated\impl\runtime\SAXUnmarshallerHandlerImpl.java
generated\impl\runtime\XMLSerializer.java
generated\impl\runtime\Util.java
generated\impl\runtime\SAXUnmarshallerHandler.java
generated\impl\runtime\AbstractUnmarshallingEventHandlerImpl.java
generated\impl\ArticleImpl.java
generated\impl\ArticleTypeImpl.java
generated\impl\CatalogImpl.java
generated\impl\CatalogTypeImpl.java
generated\impl\JAXBVersion.java
generated\impl\JournalImpl.java
generated\impl\JournalTypeImpl.java
generated\Article.java
generated\ArticleType.java
generated\Catalog.java
generated\CatalogType.java
generated\Journal.java
generated\JournalType.java
generated\ObjectFactory.java
generated\bgm.ser
generated\jaxb.properties
A Java interface and a Java class are generated corresponding to each top-level xs:element and top-level xs:complexType in the example XML Schema. A factory class (ObjectFactory.java), consisting of methods to create interface objects, also gets generated.
The ObjectFactory.java class is in this article's sample code file,
jaxb-java-resources.zip.
Catalog.java is the interface generated corresponding to the top-level element catalog. An interface generated from a schema element extends the javax.xml.bind.Element class. Catalog.java is illustrated in the listing below.
package generated;
public interface Catalog
extends javax.xml.bind.Element, generated.CatalogType
{
}
CatalogType.java is the generated interface corresponding to the top-level complexType catalogType. The CatalogType interface consists of the getter and setter methods for each of the attributes of the catalog element, and a getter method for the journal elements in the catalog element. CatalogType.java is illustrated in the following listing.
package generated;
public interface CatalogType {
java.lang.String getSection();
void setSection(java.lang.String value);
java.util.List getJournal();
java.lang.String getPublisher();
void setPublisher(java.lang.String value);
}
CatalogImpl.java and CatalogTypeImpl.java are the Java classes generated for the Catalog.java and CatalogType.java interfaces, respectively.
Creating an XML Document from the Java Classes
In this section, an example XML document shall be created from the Java classes generated with JAXB. The example XML document, catalog.xml, is illustrated in the following listing.
<?xml version="1.0" encoding="UTF-8"?>
<catalog xmlns="http://www.w3.org/2001/XMLSchema-Instance"
section="Java Technology"
publisher="IBM developerWorks">
<journal>
<article level="Intermediate" date="January-2004" >
<title>Service Oriented Architecture Frameworks </title>
<author>Naveen Balani</author>
</article>
<article level="Advanced" date="October-2003" >
<title>Advance DAO Programming</title>
<author>Sean Sullivan</author>
</article>
<article level="Advanced" date="May-2002" >
<title>Best Practices in EJB Exception Handling </title>
<author>Srikanth Shenoy </author>
</article>
</journal>
</catalog>
Create a CatalogImpl class object from the Java classes and marshal the CatalogImpl class object with a Marshaller to construct an XML document.
Creating the Marshaller
First, import the javax.xml.bind package, which consists of the Marshaller, UnMarshaller, and JAXBContext classes. The Marshaller class is used to convert a Java object into XML data. The UnMarshaller class converts an XML document to a Java object.
import javax.xml.bind.*;
Create a JAXBContext. A JAXBContext object is required to implement the JAXB binding framework operations marshal, unmarshal, and validate. An application creates a new instance (object) of the JAXBContext class with the static method newInstance(String contextPath). The contextPath specifies a list of Java package names for the schema-derived interfaces.
JAXBContext jaxbContext=JAXBContext.newInstance("generated");
The directory generated contains the JAXB-generated classes and interfaces.
Create a Marshaller with the createMarshaller method. The Marshaller class has overloaded marshal methods to marshal (that is, convert a Java object to XML data) into SAX2 events, a Document Object Model (DOM) structure, an OutputStream, a javax.xml.transform.Result, or a java.io.Writer object.
Marshaller marshaller=jaxbContext.createMarshaller();
Creating a Java Object for an XML Document: CatalogImpl
To create a Java object, first create an ObjectFactory. An implementation class instance is
created with the ObjectFactory. For each of the schema-derived Java classes, a static factory method to produce an object of the class is defined in the ObjectFactory.
ObjectFactory factory=new ObjectFactory();
Create a catalog element with the createCatalog method of the ObjectFactory class. CatalogImpl is the implementation class for the interface Catalog.
CatalogImpl catalog=(CatalogImpl)(factory.createCatalog());
Set the section attribute of the catalog element with the setSection method in the CatalogImpl class.
catalog.setSection("Java Technology");
Set the publisher attribute of the catalog element with the setPublisher method.
catalog.setPublisher("IBM developerWorks");
Creating a Java Object for an XML Document: JournalImpl and ArticleImpl
Create a journal element with the createJournal method of the ObjectFactory class. JournalImpl is the implementation class for the interface Journal.
JournalImpl journal=(JournalImpl)(factory.createJournal());
Add the journal element to the catalog element. Obtain a java.util.List of JournalImpl for a CatalogImpl and add the journal element to the List.
java.util.List journalList=catalog.getJournal();
journalList.add(journal);
Create the article element in the journal element with the createArticle method of the ObjectFactory class. ArticleImpl is the implementation class for the Article interface.
ArticleImpl article=(ArticleImpl)(factory.createArticle());
Set the level attribute of the article element with the setLevel method in the ArticleImpl class.
article.setLevel("Intermediate");
Set the date attribute of the article element with the setDate method.
article.setDate("January-2004");
Create the title element in the article element with the setTitle method.
article.setTitle("Service Oriented Architecture Frameworks");
Create the author element of the article element with the setAuthor method.
article.setAuthor("Naveen Balani");
Add the article element to the journal element. Obtain a java.util.List of ArticleImpl for a JournalImpl and add the article element to the List.
java.util.List articleList=journal.getArticle();
articleList.add(article);
Similar to the article element created with the procedure explained, add the other article elements to create the example XML document catalog.xml.
Marshalling the Java Object to an XML Document
Marshal the CatalogImpl object to an XML document with the marshal method of the class Marshaller. The CatalogImpl object is marshalled to an OutputStream.
marshaller.marshal(catalog, new FileOutputStream(xmlDocument));
xmlDocument is the output XML java.io.File object, representing the XML document shown at the beginning of this section.
JAXBConstructor.java, the program used to create an XML document from the Java classes, is in this article's sample code file,
jaxb-java-resources.zip.
Conclusion
JAXB provides a xjc binding compiler to generate Java objects from a schema, which may be subsequently marshalled to an XML document. However, JAXB has a limitation: it does not support all of the XML schema constructs.
Resources
- " Java Architecture for XML Binding"
- "XML Schema Structures"
- Java Web Services Developer Pack 1.5
- Example code for this article: jaxb-java-resources.zip
Deepak Vohra is a NuBean consultant and a web developer.
Return to ONJava.com
You must be logged in to the O'Reilly Network to post a talkback.
Showing messages 1 through 30 of 30.
-
classes are not created
2008-05-13 06:53:01 bedabo [Reply | View]
-
classes are not created
2008-05-21 19:46:35 Deepak Vohra [Reply | View]
http://www.w3.org/TR/html4/loose.dtdis a DTD. Specify a XML Schema. Please post the schema.
-
Java classes are not getting created
2008-03-04 12:14:48 Niveditha Chandrashekar [Reply | View]
setenv in C:\Sun\jwsdp-1.6\jwsdp-shared\bin looks like this
REM
REM Copyright 2004 Sun Microsystems, Inc. All rights reserved.
REM SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
REM
rem ---------------------------------------------------------------------------
rem User configurable settings
rem
rem Set configurable environment variables. By default, they are just unset.
rem These values must be set in this file as they are not inherited from the
rem shell.
rem
rem Note for Win98 and WinME users:
rem All paths must be use the short path name only i.e. the "8.3" format of
rem for the path. The long path name may cause unexpected results.
rem
rem $Id: setenv.bat,v 1.14 2004/03/30 23:27:52 ofung Exp $
rem ---------------------------------------------------------------------------
rem Warning: Donot change value of JWSDP_HOME property. Specially donot update that
rem to have value with quotes (")
set JAVA_HOME=C:\j2sdk1.4.2_12
set ANT_HOME=C:\Sun\jwsdp-1.6\apache-ant
set ANT_OPTS=-Djava.endorsed.dirs=C:\Sun\jwsdp-1.6\jaxp\lib\endorsed;C:\Sun\jwsdp-1.6\jaxp\lib
set JWSDP_HOME=C:\Sun\jwsdp-1.6
i am setting the PATH and the JAVA_HOME variable
set JAVA_HOME=C:\j2sdk1.4.2_12
set path=%JAXB_HOME%\bin; %JWSDP_HOME%\jwsdp-shared\bin;
I have placed myxsd.xsd in C:\Sun\jwsdp-1.6\jaxb\bin.
On the commandline from the above diretory when i give xjc myxsd.xsd command
Nothing is displayed on the command prompt.
And no java files are generated.
Please help.
-thanks
Niveditha
-
xjc is not creating java classes
2008-03-04 12:12:27 Niveditha Chandrashekar [Reply | View]
setenv in C:\Sun\jwsdp-1.6\jwsdp-shared\bin looks like this
REM
REM Copyright 2004 Sun Microsystems, Inc. All rights reserved.
REM SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
REM
rem ---------------------------------------------------------------------------
rem User configurable settings
rem
rem Set configurable environment variables. By default, they are just unset.
rem These values must be set in this file as they are not inherited from the
rem shell.
rem
rem Note for Win98 and WinME users:
rem All paths must be use the short path name only i.e. the "8.3" format of
rem for the path. The long path name may cause unexpected results.
rem
rem $Id: setenv.bat,v 1.14 2004/03/30 23:27:52 ofung Exp $
rem ---------------------------------------------------------------------------
rem Warning: Donot change value of JWSDP_HOME property. Specially donot update that
rem to have value with quotes (")
set JAVA_HOME=C:\j2sdk1.4.2_12
set ANT_HOME=C:\Sun\jwsdp-1.6\apache-ant
set ANT_OPTS=-Djava.endorsed.dirs=C:\Sun\jwsdp-1.6\jaxp\lib\endorsed;C:\Sun\jwsdp-1.6\jaxp\lib
set JWSDP_HOME=C:\Sun\jwsdp-1.6
i am setting the PATH and the JAVA_HOME variable
set JAVA_HOME=C:\j2sdk1.4.2_12
set path=%JAXB_HOME%\bin; %JWSDP_HOME%\jwsdp-shared\bin;
I have placed myxsd.xsd in C:\Sun\jwsdp-1.6\jaxb\bin.
On the commandline from the above diretory when i give xjc myxsd.xsd command
Nothing is displayed on the command prompt.
And no java files are generated.
Please help.
-thanks
Niveditha
-
Generating a XML document in JAXB
2007-01-18 09:02:24 Sivacham [Reply | View]
I have a schema that generates around 50 classes after i use the xjc batch file.The schema includes mandatory and optional elements.
i have a queries
1)can i automate the creation of xml document.Since i hav a schema and i have a input driven interface ie i configure the values of the elements dynamically can i bypass the usage of the java objects or can i use them more efficeintly depending on the input
-
JAXB2 blog based on this article
2006-12-21 20:42:51 zarar [Reply | View]
http://arsenalist.com/2006/12/22/jaxb2-xml-to-java-and-vice-versa-made-easy/
-
Root element not generated
2006-12-14 08:26:48 jeroenBos [Reply | View]
Hi all,
i first was using jaxb 2.0 for marshalling to xml. This worked fine a produced a nice xml string with a root element. the problem is that i can not use jre 1.5 but have to use 1.4x instead so i also need a older jaxb impl.
well no worries. now using an older impl. and still getting a XML string only without a root element.
i can not do this:
JAXBElement<nl.waternet.schemas.wml_soap_debiteur_v0001.EnvelopeType> oElement=oDebFactory.createEnvelope((nl.waternet.schemas.wml_soap_debiteur_v0001.EnvelopeType)oDebEnvelop);
because oDebFactory.createEnvelope does not allow any input params.
Please give some help here.
here is the rest of my code:
package coda.nl.wxml.helpers;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;
import java.math.BigInteger;
import java.rmi.server.UID;
import java.util.Calendar;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import nl.waternet.schemas.wgd_types_v0001.impl.AdresImpl;
import nl.waternet.schemas.wgd_types_v0001.impl.RekeningNummerImpl;
import nl.waternet.schemas.wgd_types_v0001.impl.AdresImpl.HuisNummerToevoegingTypeImpl;
import nl.waternet.schemas.wml_crediteur_v0001.WMLCrediteur;
import nl.waternet.schemas.wml_crediteur_v0001.impl.WMLCrediteurTypeImpl.ContactPersoonTypeImpl;
import nl.waternet.schemas.wml_debiteur_v0001.impl.WMLDebiteurTypeImpl;
import nl.waternet.schemas.wml_header_v0001.impl.WMLHeaderTypeImpl;
import nl.waternet.schemas.wml_soap_crediteur_v0001.Envelope;
import nl.waternet.schemas.wml_soap_crediteur_v0001.EnvelopeType;
import nl.waternet.schemas.wml_soap_crediteur_v0001.ObjectFactory;
import nl.waternet.schemas.wml_soap_crediteur_v0001.EnvelopeType.BodyType;
import nl.waternet.schemas.wml_soap_crediteur_v0001.EnvelopeType.HeaderType;
import nl.waternet.schemas.wml_soap_crediteur_v0001.impl.EnvelopeTypeImpl;
import nl.waternet.schemas.wml_soap_debiteur_v0001.impl.EnvelopeImpl;
import coda.nl.creddeb.DebCred;
import coda.nl.general.GenericFunctions;
import coda.nl.general.ValidationEventHandlerHelper;
import coda.nl.properties.Properties;
/* -------------------------------------------------------------------------------------------------------------------------------------------------
* Version Date Description
* -------------------------------------------------------------------------------------------------------------------------------------------------
* 1.0 08-12-2006 this class create a wmlenvelop
*/
/**
* @Description this class create a wmlenvelop
* @author bossenbroekj
* @Date 08-12-2006
* @version 1.0
**/
public class WMLEnvelopeHelper
{
private String GENEVELOPEERROR="Error generating evelope from DebCred Object. Message: ";
private String VALIDATIONERROR="Error validating xml WMLEnvelope. Message: ";
private DebCred m_oDebCred=null;
private Properties m_oProperties=null;
public WMLEnvelopeHelper(DebCred p_oDebCredObj, Properties p_oProperties)
{
m_oDebCred=p_oDebCredObj;
m_oProperties=p_oProperties;
}
public String generateEnvelopeFromDebCredObj()throws Exception
{
String sDebCredEnvelopeXMLStr="";
UID oUID = new UID();
AdresImpl oVestigingsAdres=null;
AdresImpl oPostAdres=null;
HuisNummerToevoegingTypeImpl oVestHuisnummerToevoeging=null;
HuisNummerToevoegingTypeImpl oPostHuisnummerToevoeging=null;
RekeningNummerImpl oRekeningNummer =null;
ContactPersoonTypeImpl oCreditorContactPersoon=null;
nl.waternet.schemas.wml_debiteur_v0001.impl.WMLDebiteurTypeImpl.ContactPersoonTypeImpl oDebitorContactPersoon=null;
BigInteger biVHuisnummer = null;
BigInteger biPHuisnummer = null;
WMLCrediteurHelper oCrediteurHelper=null;
WMLDebiteurHelper oDebiteurHelper=null;
WMLCrediteur oCrediteur=null;
WMLDebiteurTypeImpl oDebiteur=null;
WMLHeaderTypeImpl oWmlHeader=null;
String sMinorVersieDeb=m_oProperties.getMinorVersieDeb();
String sMajorVersieDeb=m_oProperties.getMajorVersieDeb();
String sMajorVersieCred=m_oProperties.getMajorVersieCred();
String sMinorVersieCred=m_oProperties.getMinorVersieCred();
String sExternid=m_oProperties.getExternId();
String sInterId=oUID.toString();//maybe property?
String sAppNaamOntvanger=m_oProperties.getAppNaamOnt();
String sAuthenticate=m_oProperties.getAutentificatieOnt();
String sGebruikerOntvanger=m_oProperties.getGebruikerOnt();
String sAppNaamVerzender=m_oProperties.getAppNaamVer();
String sGebruikerVerzender=m_oProperties.getGebruikerVer();
Calendar oStartDate =null;
Calendar oEndDate =null;
JAXBContext oContext= null;
Marshaller oMarshaller=null;
StringWriter oWriter=null;
try
{
//set startdate
oStartDate=GenericFunctions.oCreateCalendarFromSystemDate();
//set enddate after object has been generated
//generate wmlheade
oWmlHeader=new WMLHeaderTypeImpl();
WMLHeaderHelper oWMLHeaderHelper=new WMLHeaderHelper();
oWMLHeaderHelper.setOntvanger(oWmlHeader,sAppNaamOntvanger,sAuthenticate,sGebruikerOntvanger);
//generate body
//set addresses
//vestigingsadres
oVestigingsAdres=new AdresImpl();
//set bigint huisnummer
biVHuisnummer = new BigInteger(m_oDebCred.getVHUISNUMMER());
oVestigingsAdres.setHuisNummer(biVHuisnummer);
if(!(m_oDebCred.getVHUISNUMMERTOEVOEGING()==null||m_oDebCred.getVHUISNUMMERTOEVOEGING().equals("")))
{
oVestHuisnummerToevoeging=new HuisNummerToevoegingTypeImpl();
oVestHuisnummerToevoeging.setWaternetToevoeging(m_oDebCred.getVHUISNUMMERTOEVOEGING());
oVestigingsAdres.setHuisNummerToevoeging(oVestHuisnummerToevoeging);
}
oVestigingsAdres.setLandCode(m_oDebCred.getVLANDCODE());
oVestigingsAdres.setPlaatsNaam(m_oDebCred.getVPLAATSNAAM());
oVestigingsAdres.setPostCode(m_oDebCred.getVPOSTCODE());
oVestigingsAdres.setStraatNaam(m_oDebCred.getVSTRAATNAAM());
//postadres
oPostAdres=new AdresImpl();
//set bigint huisnummer
biPHuisnummer = new BigInteger(m_oDebCred.getPHUISNUMMER());
oPostAdres.setStraatNaam(m_oDebCred.getPSTRAATNAAM());
oPostAdres.setHuisNummer(biPHuisnummer);
if(!(m_oDebCred.getPHUISNUMMERTOEVOEGING()==null||m_oDebCred.getPHUISNUMMERTOEVOEGING().equals("")))
{
oPostHuisnummerToevoeging=new HuisNummerToevoegingTypeImpl();
oPostHuisnummerToevoeging.setWaternetToevoeging(m_oDebCred.getPHUISNUMMERTOEVOEGING());
oPostAdres.setHuisNummerToevoeging(oPostHuisnummerToevoeging);
}
oPostAdres.setLandCode(m_oDebCred.getPLANDCODE());
oPostAdres.setPlaatsNaam(m_oDebCred.getPPLAATSNAAM());
oPostAdres.setPostCode(m_oDebCred.getPPOSTCODE());
//set accountnumber
//is postbank or bank
oRekeningNummer=new RekeningNummerImpl();
if(m_oDebCred.getPOSTBANK().equalsIgnoreCase("J"))
{
oRekeningNummer.setGiroRekeningNummer(m_oDebCred.getREKENINGNUMMER());
}
else
{
oRekeningNummer.setBankRekeningNummer(m_oDebCred.getREKENINGNUMMER());
}
//append to debitor or creditor
//wmlcreditor or wmldebtor
if(m_oDebCred.getBERICHTTYPE().equalsIgnoreCase("Crediteur"))
{
ObjectFactory oFactory=new ObjectFactory();
EnvelopeTypeImpl oEnvelop=new EnvelopeTypeImpl();
BodyType oBody=oFactory.createEnvelopeTypeBodyType();
oCrediteurHelper=new WMLCrediteurHelper();
//check contactpersoon
if(!(m_oDebCred.getCONTACTPNAAM()==null||m_oDebCred.getCONTACTPNAAM().equals("")))
{
oCreditorContactPersoon=new ContactPersoonTypeImpl();
oCreditorContactPersoon.setFaxNummer(m_oDebCred.getCONTACTPFAXNUMMER());
oCreditorContactPersoon.setWerkTelefoonNummer(m_oDebCred.getCONTACTPWERKTELEFOON());
oCreditorContactPersoon.setNaam(m_oDebCred.getCONTACTPNAAM());
}
oCrediteur=oCrediteurHelper.generateWMLCreditor(m_oDebCred.getCREDDEBNUM(),m_oDebCred.getCREDDEBNAAM(),m_oDebCred.getWERKTELEFOON(),m_oDebCred.getFAXNUMMER(),oVestigingsAdres,oPostAdres,oRekeningNummer,oCreditorContactPersoon,m_oDebCred.getINDGEBLOKKEERD());
//set body
oBody.setWMLCrediteur(oCrediteur);
//set header
HeaderType oHeader=oFactory.createEnvelopeTypeHeaderType();
//set berichtgegevens
oWMLHeaderHelper.setBerichtGegevens(oWmlHeader,"PUBLISH","Crediteur",sExternid,sInterId,sMajorVersieCred,sMinorVersieCred,m_oDebCred.getMUTATIESOORT());
//first set enddate
oEndDate=GenericFunctions.oCreateCalendarFromSystemDate();
oWMLHeaderHelper.setVerzender(oWmlHeader,sAppNaamVerzender,oStartDate,oEndDate,sGebruikerVerzender);
oHeader.setWMLHeader(oWmlHeader);
oEnvelop.setHeader(oHeader);
oEnvelop.setBody(oBody);
//end header
//set sDebCredEnvelopeXMLStr
oContext = JAXBContext.newInstance("nl.waternet.schemas.wml_soap_crediteur_v0001");
oMarshaller = oContext.createMarshaller();
oMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
oWriter = new StringWriter();
oMarshaller.marshal(oEnvelop,oWriter) ;
sDebCredEnvelopeXMLStr=oWriter.toString();
oWriter.close();
}
else
{
nl.waternet.schemas.wml_soap_debiteur_v0001.ObjectFactory oDebFactory=new nl.waternet.schemas.wml_soap_debiteur_v0001.ObjectFactory();
//nl.waternet.schemas.wml_soap_debiteur_v0001.impl.EnvelopeTypeImpl oDebEnvelop=new nl.waternet.schemas.wml_soap_debiteur_v0001.impl.EnvelopeTypeImpl();
nl.waternet.schemas.wml_soap_debiteur_v0001.EnvelopeType.BodyType oDebBody=oDebFactory.createEnvelopeTypeBodyType();
//nl.waternet.schemas.wml_soap_debiteur_v0001
oDebiteurHelper=new WMLDebiteurHelper();
nl.waternet.schemas.wml_soap_debiteur_v0001.impl.EnvelopeTypeImpl oDebEnvelop=(nl.waternet.schemas.wml_soap_debiteur_v0001.impl.EnvelopeTypeImpl)(oDebFactory.createEnvelopeType());
//check contactpersoon
if(!(m_oDebCred.getCONTACTPNAAM()==null||m_oDebCred.getCONTACTPNAAM().equals("")))
{
oDebitorContactPersoon=new nl.waternet.schemas.wml_debiteur_v0001.impl.WMLDebiteurTypeImpl.ContactPersoonTypeImpl();
oDebitorContactPersoon.setFaxNummer(m_oDebCred.getCONTACTPFAXNUMMER());
oDebitorContactPersoon.setWerkTelefoonNummer(m_oDebCred.getCONTACTPWERKTELEFOON());
oDebitorContactPersoon.setNaam(m_oDebCred.getCONTACTPNAAM());
}
oDebiteur =oDebiteurHelper.generateWMLDebtor(m_oDebCred.getCREDDEBNUM(),m_oDebCred.getCREDDEBNAAM(),m_oDebCred.getWERKTELEFOON(),m_oDebCred.getFAXNUMMER(),oVestigingsAdres,oPostAdres,oRekeningNummer,oDebitorContactPersoon,m_oDebCred.getINDGEBLOKKEERD());
//set body
oDebBody.setWMLDebiteur(oDebiteur);
//set header
nl.waternet.schemas.wml_soap_debiteur_v0001.EnvelopeType.HeaderType oDebHeader=oDebFactory.createEnvelopeTypeHeaderType();
oWMLHeaderHelper.setBerichtGegevens(oWmlHeader,"PUBLISH","DEBITEUR",sExternid,sInterId,sMajorVersieDeb,sMinorVersieDeb,m_oDebCred.getMUTATIESOORT());
//first set enddate
oEndDate=GenericFunctions.oCreateCalendarFromSystemDate();
oWMLHeaderHelper.setVerzender(oWmlHeader,sAppNaamVerzender,oStartDate,oEndDate,sGebruikerVerzender);
oDebHeader.setWMLHeader(oWmlHeader);
oDebEnvelop.setHeader(oDebHeader);
oDebEnvelop.setBody(oDebBody);
//end header
//set sDebCredEnvelopeXMLStr
oContext = JAXBContext.newInstance("nl.waternet.schemas.wml_soap_debiteur_v0001");
oMarshaller = oContext.createMarshaller();
oMarshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE );
oWriter = new StringWriter();
//JAXBElement<nl.waternet.schemas.wml_soap_debiteur_v0001.EnvelopeType> oElement=oDebFactory.createEnvelope((nl.waternet.schemas.wml_soap_debiteur_v0001.EnvelopeType)oDebEnvelop);
//marshaller.marshal(catalogElement, new FileOutputStream(xmlDocument));
oMarshaller.marshal(oDebEnvelop,oWriter) ;
sDebCredEnvelopeXMLStr=oWriter.toString();
oWriter.close();
}
//end body
}
catch (Exception oEx)
{
throw new Exception(GenericFunctions.generateLogMessage("WMLEnvelopeHelper","generateEnvelopeFromDebCredObj",GENEVELOPEERROR+oEx.getMessage()));
}
return sDebCredEnvelopeXMLStr;
}
public boolean validateXmlEnvelope(String p_sEnvelope, String p_sBerichtTypeInstance, String p_sSchemaLocation)throws Exception
{
boolean bIsValid=true;
Unmarshaller oUnmarshaller=null;
JAXBContext oContext=null;
try
{
//validate xml
oContext = JAXBContext.newInstance(p_sBerichtTypeInstance);
oUnmarshaller = oContext.createUnmarshaller();
SAXParserFactory oSAXParserFactory = SAXParserFactory.newInstance();
SchemaFactory oSf = SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema oSchema = oSf.newSchema(new File(p_sSchemaLocation));
oSAXParserFactory.setSchema(oSchema);
oSAXParserFactory.setValidating(true);
oUnmarshaller.setSchema(oSchema);
ValidationEventHandlerHelper oValidateEventHandler=new ValidationEventHandlerHelper();
oUnmarshaller.setEventHandler(oValidateEventHandler);
oUnmarshaller.unmarshal(new StreamSource(new StringReader(p_sEnvelope)));
if(!oValidateEventHandler.bIsValid)
{
throw new Exception(oValidateEventHandler.sValidationMessage);
}
}
catch (Exception oEx)
{
throw new Exception(GenericFunctions.generateLogMessage("WMLEnvelopeHelper","validateXmlEnvelope",VALIDATIONERROR+oEx.getMessage()));
}
return bIsValid;
}
}
-
Root element not generated
2006-12-14 08:33:20 Deepak Vohra [Reply | View]
Actually JWSDP 2.0 requires JDK 5.0.
Root element gets generated with JDK 1.4.X also. -
Root element not generated
2006-12-14 08:31:00 Deepak Vohra [Reply | View]
Use JWSDP 2.0 with JDK 1.4.x.
JWSDP 2.0 has the JAXB 2.0 implementation. -
Root element not generated
2006-12-14 09:05:44 jeroenBos [Reply | View]
But when using jaxb 2.0 and using the xjc tool for generating objects from xsd's it tells me to use jdk 1.5.
the code posted works, only no root element is created. Do you have any idea how to solve this?
Or can i edit the xjc.bat that is uses 1.4x jdk?
thanks!
-
XML to Java to XML..
2006-10-27 00:27:50 AshBoy [Reply | View]
I have an XML document. Now I need to create an XML with same structure populate it with lots of data. The XML document can vary.. and hence the way i thought to solve the above problem is..
Read the XML document. Generate Java classes corresponding to it. Create multiple Java objects. And finally create an XML document using these objects.. Is the process correct and can it be achieved through JAXB.
Please Help.
-
JAXB 2.0 - JAXBConstructor Code
2006-03-28 20:00:11 vp17in [Reply | View]
Here is the code for JAXBConstructor in JAXB 2.0
package generated;
import generated.*;
import javax.xml.bind.*;
import org.w3c.dom.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class JAXBConstructor {
public void generateXMLDocument(File xmlDocument){
try {
JAXBContext jaxbContext=JAXBContext.newInstance("generated");
Marshaller marshaller=jaxbContext.createMarshaller();
generated.ObjectFactory factory=new generated.ObjectFactory();
CatalogType catalog = factory.createCatalogType();
catalog.setSection("Java Technology");
catalog.setPublisher("IBM developerWorks");
JournalType journal = factory.createJournalType();
ArticleType article = factory.createArticleType();
article.setLevel("Intermediate");
article.setDate("January-2004");
article.setTitle("Service Oriented Architecture Frameworks");
article.setAuthor("Naveen Balani");
java.util.List journalList=catalog.getJournal();
journalList.add(journal);
java.util.List articleList=journal.getArticle();
articleList.add(article);
article=factory.createArticleType();
article.setLevel("Advanced");
article.setDate("October-2003");
article.setTitle("Advance DAO Programming");
article.setAuthor("Sean Sullivan");
articleList=journal.getArticle();
articleList.add(article);
article=factory.createArticleType();
article.setLevel("Advanced");
article.setDate("May-2002");
article.setTitle("Best Practices in EJB Exception Handling");
article.setAuthor("Srikanth Shenoy");
articleList=journal.getArticle();
articleList.add(article);
JAXBElement<CatalogType> catalogElement=factory.createCatalog(catalog);
marshaller.marshal(catalogElement, new FileOutputStream(xmlDocument));
}catch (IOException e) {
System.out.println(e.toString());
}catch (JAXBException e) {
System.out.println(e.toString());
}
}
public static void main (String[] argv) {
String xmlDocument=argv[0];
JAXBConstructor jaxbConstructor=new JAXBConstructor();
jaxbConstructor.generateXMLDocument(new File(xmlDocument));
}
}
-
JAXB - Thanks
2006-03-28 05:04:38 vp17in [Reply | View]
Hello Deepak Vohra
I was using JAXB 2.0 and didn't notice your comments section with the update. I was struggling with which jar files to set in classpath. Thank god I found it. Thank you very much for getting back to the article and updating with JAXB 2.0.
Regards
Vishnu
-
JAXB 2.0
2006-03-19 07:16:16 Deepak Vohra [Reply | View]
For JAXB 2.0 the JAR files required and the Java classes generated are different.
1. JAXB 2.0 requires JDK 5.0, because JAXB 2.0 makes use of parameterized types.
2. For JAXB 2.0 the JAR files required are :
C:\Sun\jwsdp-2.0\jaxb\lib\jaxb-api.jar,C:\Sun\jwsdp-2.0\jaxb\lib\jaxb-impl.jar,C:\Sun\jwsdp-2.0\jaxb\lib\jaxb-xjc.jar,C:\Sun\jwsdp-2.0\jwsdp-shared\lib\activation.jar,
C:\Sun\jwsdp-2.0\sjsxp\lib\jsr173_api.jar,C:\Sun\jwsdp-2.0\sjsxp\lib\sjsxp.jar
3. For JAXB 2.0 a value class is generated for each top level complexType, instead of an interface and a implementation class. An ObjectFactory method is generated for each op level element.
4. For marshalling with JAXB 2.0, marshall withJAXBElement<CatalogType>object, instead of CatalogType object. CatalogType is value class corresponding to root element complexType catalogType.
//Create a CatalogType object
CatalogType catalog = factory.createCatalogType();
//Add elements and attributes to CatalogType object.
//Obtain a JAXBElement object from CatalogType object and marshall with the JAXBElement element.
JAXBElement<CatalogType> catalogElement=factory.createCatalog(catalog);
marshaller.marshal(catalogElement, new FileOutputStream(xmlDocument));
5. For unmarshalling with JAXB 2.0, unmarshalling returns a JAXBElement object.
JAXBContext jaxbContext = JAXBContext.newInstance("generated");
Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
JAXBElement<CatalogType> catalogElement = (JAXBElement<CatalogType>)
unMarshaller.unmarshal(xmlDocument);
//Obtain a CatalogType object from JAXBElement object.
CatalogType catalog=catalogElement.getValue();
-
JAXB1.4 | Root element of the schema is not created
2006-07-26 23:37:45 Gowtham_J [Reply | View]
Hi Deepak, I am working on JXB1.4 to create the XML document by binding the XML schema. Everything is fine except the Root element generation. My root element is not at all created. For marshalling, i am giving the root element object. But it didnt worked. what could be the reason/reasons???
Hope you can help me to get rid of this problem.
Thanks in advance.
Gowtham J
-
JAXB1.4 | Root element of the schema is not created
2006-07-27 11:30:10 Deepak Vohra [Reply | View]
To marshall, we need to follow the following steps:
1. Create a JAXBContext object and use this object to create a Marshaller object.
2. Create an ObjectFactory object to create instances of relevant generated Java content classes.
3. Using the ObjectFactory object, create an object tree with RootType as the root object. Populate these tree objects with relevant data using the appropriate setter methods.
4. Create a JAXBElement<<i>RootType> object from CatalogType object. JAXBElement<<i>RootType> represents catalog element in XML document.
RootType is the interface corresponding to the root element in schema. -
JAXB1.4 | Root element of the schema is not created
2006-07-27 11:32:01 Deepak Vohra [Reply | View]
Modify 4.
4. Create a JAXBElement<RootType> object from RootType object. JAXBElement<RootType> represents root element in XML document. -
JAXB 2.0
2006-07-20 09:05:18 gpaladi [Reply | View]
Hello,
I tried all steps you have mentioned for JAXB 2.0. But when I run XJC, it's not creating all classes. I try to ran the sample catalog.xsd you have mentioned in the article. It created only the following 4 files.
ArticleType
CatalogType
JournalType
ObjectFactory
Can you please help to fix this problem.
Thanks
Guru -
JAXB 2.0
2006-07-20 09:28:20 Deepak Vohra [Reply | View]
That's all the classes JAXB 2.0 creates, just the value classes, unlike JAXB 1.0 which creates interfaces and implementation classes, another advantage of JAXB 2.0.
-
What limitations ?
2004-12-21 01:24:00 Jerome_from_contrepeteries.free.fr [Reply | View]
The conclusion speaks about limitations to JAXB, what are they ?
As in previous comments, my opinion is that the title is incorrect as the article is about jaxb.
A word about hyperjaxb (xsd to hibernate classes) would be good.
My 2 cents
Jerome
-
What limitations ?
2004-12-21 05:09:29 Deepak Vohra [Reply | View]
As mentioned in the conclusion the limitation is, JAXB does not support all of the schema constructs.
-
False advertisement
2004-12-16 07:29:46 eg344 [Reply | View]
The title of the article is POJOs to XML and back. The article discusses on how to go from a schema to java, not the other way around (which are two completely different things), the objects are not POJO because they extend JAXB interfaces, and the code shown is one way. -
False advertisement
2004-12-17 05:12:10 Deepak Vohra [Reply | View]
A more appropriate title is,
<h4>XML to Java Objects and Back</h4> -
False advertisement
2004-12-17 05:12:53 Deepak Vohra [Reply | View]
A more appropriate title is,
XML to Java Objects and Back
-
False advertisement
2004-12-21 11:45:58 Chris Adamson [Reply | View]
This is a good point. Per this feedback, I've changed the blurb to "XML to POJOs and back"
--Chris Adamson, "invalidname", ONJava editor -
False advertisement
2004-12-16 08:53:25 Deepak Vohra [Reply | View]
The tutorial discusses XML Schema to java objects and java objects to XML document.
-
XML Document Format
2004-12-16 05:31:18 Deepak Vohra [Reply | View]
To format the output XML document( with line breaks and indentation) set theMarshallerpropertyjaxb.formatted.output.
marshaller.setProperty("jaxb.formatted.output", java.lang.Boolean.TRUE);





>xjc catalog.xsd
I get:
parsing a schema...
[ERROR] The declaration for the entity "HTML.Version" must end with '>'.
line 31 of http://www.w3.org/TR/html4/loose.dtd
Failed to parse a schema.
I'm using JWSDP 2.0, JDK 1.6.0_0.5
What's the problem here?
Thank you very much for a hint?
Beda