JAXB Interview Questions and Answers
Freshers / Beginner level questions & answers
Ques 1. What Is XML Binding?
Maps XML to in-memory objects according to a schema. Generates classes to represent XML elements so developers don't have to write them the binding compiler does this the classes follow JavaBeans property access conventions. Supports three primary operations:
- Marshalling a tree of objects into an XML document
- Unmarshalling an XML document into a tree of objects
- Includes validation of the XML against the schema
Ques 2. What is XML Binding Relationships?
The relationships between the components involved in XML binding (data binding) are shown below:
- Schema generates classes.
- Objects are instanceof classes.
- Marshal from objects to XML.
- Unmarshall from XML to objects.
- XML validates and conforms to Schema.
Ques 3. Why Use XML Binding?
- It's not necessary. Everything that must be done with XML can be done with SAX and DOM.
- It's easier, don't have to write as much code, don't have to learn SAX and/or DOM.
- It's less error-prone, all the features of the schema are utilized, don't have to remember to manually implement them.
- It can allow customization of the XML structure unlike XMLEncoder and XMLDecoder in the java.beans package.
Ques 4. Please explain JAXB Use Cases.
- Create/Read/Modify XML using Java but without using SAX or DOM.
- Validate user input using rules described in XML Schemas.
- Use XML-based configuration files, access their values, write tools that creates and modifies these files.
Ques 5. What are the goals of JAXB?
- Easy to use require minimal XML knowledge, don't require SAX/DOM knowledge.
- Customizable can customize mapping of XML to Java.
- Portable can change JAXB implementation without changing source code.
- Deliver soon, deliver core functionality ASAP.
- Follow standard design and naming conventions in generated Java.
- Match schema, easy to identify generated Java components that correspond to schema features.
- Hide plumbing encapsulate implementation of unmarshalling, marshalling and validation.
- Validation, on demand validate objects without requiring marshalling.
- Preserve object equivalence (round tripping), marshalling objects to XML and unmarshalling back to objects results in equivalent objects.
Ques 6. What are the disadvantages/non-goals of JAXB?
Standardize generated Java
classes generated by different
JAXB implementations may not be
compatible with each other
Preserve XML equivalence
unmarshalling XML to objects and
marshalling back to XML may not
result in equivalent XML
Bind existing JavaBeans
to schemas
can only marshal and unmarshal
classes generated by JAXB
may be added later
Schema evolution support
can t modify previously generated
code to support schema changes
must generated new code
Allow generated Java to access
XML elements/attributes not
described in initial schema
Partial binding
unmarshalling only a subset
of an XML document
breaks round tripping
Implement every feature of the
schema language
it s tough to implement
all of XML Schema!
Support DTDs
focusing on XML Schema
DTDs were supported in an earlier
version, but won t be anymore
tools for converting DTDs to
XML Schemas exist
Ques 7. Give me an example of XSD.
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema elementFormDefault="qualified"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://www.withoutbook.com/cars"
targetNamespace="http://www.withoutbook.com/cars">
<xs:complexType name="car">
<xs:sequence>
<xs:element name="make" type="xs:string"/>
<xs:element name="model" type="xs:string"/>
<xs:element name="color" type="xs:string"/>
</xs:sequence>
<xs:attribute name="year" type="xs:positiveInteger" use="required"/>
</xs:complexType>
<xs:element name="cars">
<xs:complexType>
<xs:sequence>
<xs:element name="car" type="car" maxOccurs="unbounded"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Ques 8. Give me an example of XML document.
<?xml version="1.0" encoding="UTF-8"?>
<cars xmlns="http://www.withoutbook.com/cars"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.withoutbook.com/cars cars.xsd">
<car year="2001">
<make>BMW</make>
<model>Z3</model>
<color>yellow</color>
</car>
<car year="2001">
<make>Honda</make>
<model>Odyssey</model>
<color>green</color>
</car>
<car year="1997">
<make>Saturn</make>
<model>SC2</model>
<color>purple</color>
</car>
</cars>
Ques 9. How to generate Java from XML Schema. Please show the example.
From command-line
Windows: %JAXB_HOME%binxjc cars.xsd
UNIX: %JAXB_HOME%/bin/xjc.sh cars.xsd
these write generated files to current directory
From Ant
<java jar="${env.JAXB_HOME}/lib/jaxb-xjc.jar" fork="yes">
<arg line="-d ${gen.src.dir} cars.xsd"/>
</java>
Generated Files:
com/withoutbook/cars directory
Car.java
interface representing the car complex type
only describes get and set methods for car properties
Cars.java
interface representing cars global element
extends CarsType and javax.xml.bind.Element (just a marker interface)
describes no additional methods
CarsType.java
interface representing anonymous complex type
defined inside the cars global element
provides method to get collection of Car objects (as a java.util.List)
ObjectFactory.java
class used to create objects of the above interface types
extends DefaultJAXBContextImpl which extends JAXBContext
bgm.ser
a serialized object of type com.sun.msv.grammar.trex.TREXGrammar
cant find any documentation on this - dont know its purpose
jaxb.properties
sets a property that defines the class used to create JAXBContext objects
com/withoutbook/cars/impl directory
CarImpl.java
class that implements Car
corresponds to the car XML Schema complexType
CarsTypeImpl.java
class that implements CarType
corresponds to the XML Schema anonymous type inside the cars element
CarsImpl.java
class that extends CarsTypeImpl and implements Cars
corresponds to the cars XML Schema element
Ques 10. How to unmarshall XML into Java objects? Convert from XML to Java objects.
Example
ObjectFactory factory = new ObjectFactory();
Unmarshaller u = factory.createUnmarshaller();
Cars cars = (Cars) u.unmarshal(new FileInputStream("cars.xml"));
unmarshal method accepts
java.io.File
java.io.InputStream
java.net.URL
javax.xml.transform.Source
related to XSLT
org.w3c.dom.Node
related to DOM
org.xml.sax.InputSource
related to SAX
Other Unmarshaller methods
void setValidating(boolean validating)
true to enable validation during unmarshalling; false to disable (the default)
boolean setEventHandler(ValidationEventHandler handler)
handleEvent method of ValidationEventHandler is called
if validation errors are encountered during unmarshalling
default handler terminates marshalling after first error
return true to continue unmarshalling
return false to terminate with UnmarshalException
see discussion of ValidationEventCollector later
Ques 11. Java code for marshalling Java objects into XML.
Example
Marshaller m = factory.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
Writer fw = new FileWriter("newCars.xml");
m.marshal(cars, fw);
marshal method accepts
java.io.OutputStream
java.io.Writer
javax.xml.transform.Result
related to XSLT
org.w3c.dom.Node
related to DOM
org.xml.sax.ContentHandler
related to SAX
Other Marshaller methods
boolean setEventHandler(ValidationEventHandler handler)
same as use with Unmarshaller, but validation events
are delivered during marshalling
void setProperty(String name, Object value)
supported properties are
jaxb.encoding - value is a String
» the encoding to use when marshalling; defaults to UTF-8
jaxb.formatted.output - value is a Boolean
» true to output line breaks and indentation; false to omit (the default)
jaxb.schemaLocation - value is a String
» to specify xsi:schemaLocation attribute in generated XML
jaxb.noNamespaceSchemaLocation - value is a String
» to specify xsi:noNamespaceSchemaLocation attribute in generated XML
Ques 12. Java example/java program to set object for generating XML.
Cars cars = factory.createCars();
Car car = factory.createCar();
car.setColor("blue");
car.setMake("Mazda");
car.setModel("Miata");
car.setYear(BigInteger.valueOf(2012));
cars.getCar().add(car);
car = factory.createCar();
car.setColor("red");
car.setMake("Ford");
car.setModel("Mustang II");
car.setYear(BigInteger.valueOf(2011));
cars.getCar().add(car);
Ques 13. How to validate java objects?
The graph of Java objects can contain invalid data
could occur when objects created by unmarshalling are modified
could occur when objects are created from scratch
Use a Validator to validate the objects
Example
Validator v = factory.createValidator();
try {
v.validateRoot(cars);
v.validate(car);
} catch (ValidationException e) {
// Handle the validation error described by e.getMessage().
}
Other Validator methods
boolean setEventHandler(ValidationEventHandler handler)
handleEvent method of ValidationEventHandler is called
if validation errors are encountered
default handler terminates marshalling after first error
return true to continue validating
return false to terminate with ValidationException
Pass an instance of javax.xml.bind.util.ValidationEventCollector
(in jaxb-api.jar) to setEventHandler to collect validation errors and
query them later instead of handling them during validation.
ValidationEventCollector vec =
new ValidationEventCollector();
v.setEventHandler(vec);
v.validate(cars);
ValidationEvent[] events = vec.getEvents();
Most helpful rated by users:
- What Is XML Binding?
- What is XML Binding Relationships?
- Please explain JAXB Use Cases.
- Why Use XML Binding?
- What are the goals of JAXB?