Explore topic-wise InterviewSolutions in .

This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.

1.

Java Code For Marshalling Java Objects Into Xml?

Answer»

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

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:

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

2.

What Is The Syntax Of Schemabindings?

Answer»

The syntax for the schemaBindings ELEMENT is

<jxb:schemaBindings>

<jxb:PACKAGE [name="package-name"]>

<jxb:JAVADOC> ... javadoc ... </jxb:javadoc>

</package>

<jxb:nameXmlTransform>

<jxb:typeName PREFIX="prefix" suffix="suffix"/>

<jxb:elementName prefix="prefix" suffix="suffix"/>

<jxb:modelGroupName prefix="prefix" suffix="suffix"/>

<jxb:anonymousTypeName prefix="prefix" suffix="suffix"/>

</jxb:nameXmlTransform>

</jxb:schemaBindings>

– every element and attribute WITHIN schemaBindings is optional

The syntax for the schemaBindings element is

<jxb:schemaBindings>

<jxb:package [name="package-name"]>

<jxb:javadoc> ... javadoc ... </jxb:javadoc>

</package>

<jxb:nameXmlTransform>

<jxb:typeName prefix="prefix" suffix="suffix"/>

<jxb:elementName prefix="prefix" suffix="suffix"/>

<jxb:modelGroupName prefix="prefix" suffix="suffix"/>

<jxb:anonymousTypeName prefix="prefix" suffix="suffix"/>

</jxb:nameXmlTransform>

</jxb:schemaBindings>

– every element and attribute within schemaBindings is optional

3.

Discuss Global Bindings Attributes?

Answer»

collectionType:

  • “indexed” (uses array and provides methods to get/set elements) or fully-qualified-java-class-name(must implement java.util.List)
  • default is “java.util.ArrayList”

enableFailFastCheck:

  • "true” or “false” (default)
  • if true, invalid property values are reported as soon as they are set, instead of waiting until validation is requested
  • not implemented yet in RI

generateIsSetMethod:

  • “true” or “false” (default)
  • if true, generates isSet and unSet methods for the property

underscoreBinding

  • “asCharInWord” or “asWordSeparator” (default)
  • if “asWordSeparator” , underscores in XML NAMES are removed and words are camel-cased to form Java name
  • for example, “gear_shift_knob” goes to “gearShiftKnob”

bindingStyle (was modelGroupAsClass):

  • “modelGroupBinding” or “elementBinding” (default)

choiceContentProperty:

  • “true” or “false” (default)
  • allows objects to hold one of a number of property choices which may each have a different data type

enableJavaNamingConventions:

  • “true” (default) or “false”

fixedAttributeAsConstantProperty:

  • “true” or “false” (default)
  • if true, “fixed” attributes will be represented as constants

typesafeEnumBase:

  • “xsd:string” , “xsd:decimal” , “xsd:float” , “xsd:double” or “xsd:NCName” (default)
  • DEFINES field type used to represent enumerated values in generated typesafe enum class

typesafeEnumMemberName:

  • “generateName” or “generateError” (default)
  • specifies what to do if an enumerated value cannot be MAPPED to a valid Java identifier
  • “generateName” generates names in the form VALUE_#
  • “generateError” reports an error

collectionType:

enableFailFastCheck:

generateIsSetMethod:

underscoreBinding

bindingStyle (was modelGroupAsClass):

choiceContentProperty:

enableJavaNamingConventions:

fixedAttributeAsConstantProperty:

typesafeEnumBase:

typesafeEnumMemberName:

4.

Discuss Customization Levels?

Answer»

Customizations can be made at four levels

global:

  • DEFINED at “top level” in a element
  • APPLIES to all SCHEMA elements in the source schema and in all included/imported schemas (recursively)

schema:

  • defined at “top level” in a element
  • applies to all schema elements in the target namespace of the source schema

definition:

  • defined in a TYPE or global declaration
  • applies to all schema elements that REFERENCE the type or global declaration

component:

  • defined in a particular schema element or attribute declaration
  • applies only to it

Customizations can be made at four levels

global:

schema:

definition:

component:

5.

Explain The Syntax Of Customization?

Answer»

Customizations can be specified in

  • the XML SCHEMA (our focus)
  • a binding declarations XML DOCUMENT (not WELL supported by RI yet)

The XML Schema must declare

the JAXB namespace and version

xmlns:jxb="HTTP://java.sun.com/xml/ns/jaxb"

jxb:version="1.0">

Customization elements are placed in annotation elements

 <xsd:annotation>

<xsd:appinfo>

 binding declarations

</xsd:appinfo>

</xsd:annotation>

Customizations can be specified in

The XML Schema must declare

the JAXB namespace and version

xmlns:jxb="http://java.sun.com/xml/ns/jaxb"

jxb:version="1.0">

Customization elements are placed in annotation elements

 <xsd:annotation>

<xsd:appinfo>

 binding declarations

</xsd:appinfo>

</xsd:annotation>

6.

Explain Customizing Type Bindings?

Answer»

Default bindings can be overridden:

  • at global scope
  • on case-by-case basis

Customizations include

  • names of GENERATED package, CLASSES and METHODS
  • method return TYPES
  • class property (field) types
  • which elements are bound to classes, as opposed to being IGNORED
  • class property to which each attribute and element declaration is bound

Default bindings can be overridden:

Customizations include

7.

How To Validate Java Objects?

Answer»

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();

The graph of Java objects can contain invalid data:

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

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();

8.

Java Example/java Program To Set Object For Generating Xml?

Answer»

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);

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);

9.

How To Unmarshall Xml Into Java Objects? Convert From Xml To Java Objects?

Answer»

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 UnmarshalExceptio
SEE discussion of ValidationEventCollector later

Example:

ObjectFactory factory = new ObjectFactory();

Unmarshaller u = factory.createUnmarshaller();

Cars cars = (Cars) u.unmarshal(new FileInputStream(“cars.xml”));

unmarshal method accepts:

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 UnmarshalExceptio
• see discussion of ValidationEventCollector later

10.

How To Generate Java From Xml Schema. Please Show The Example?

Answer»

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
  • can’t find any documentation on this - don’t 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 

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:

Cars.java:

CarsType.java:

ObjectFactory.java:

bgm.ser:

jaxb.properties:

CarImpl.java:

CarsTypeImpl.java:

CarsImpl.java:

11.

Give Me An Example Of Xml Document?

Answer»

&LT;?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>

<?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>

12.

Give Me An Example Of Xsd?

Answer»

&LT;?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>

<?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>

13.

What Are The Disadvantages/non-goals Of Jaxb?

Answer»

STANDARDIZE generated Java:

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

Standardize generated Java:

Preserve XML equivalence:

Bind existing JavaBeans to schemas:

Schema evolution support:

Allow generated Java to access:

XML elements/attributes not described in initial schema

Partial binding:

Implement every feature of the schema language:

Support DTDs:

14.

What Are The Goals Of Jaxb?

Answer»

Easy to use:

Customizable:

  • can customize mapping of XML to Java

Portable:

  • can change JAXB implementation without changing source code

Deliver soon:

  • deliver core functionality ASAP

Natural:

  •  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

Easy to use:

Customizable:

Portable:

Deliver soon:

Natural:

Match schema:

Hide plumbing:

Validation on demand:

Preserve object equivalence:

(round tripping)

15.

Explain Jaxb Use Cases?

Answer»

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

Create/Read/Modify XML using Java

Validate user input:

Use XML-based configuration files

16.

Why Use Xml Binding?

Answer»

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

It’s not necessary

It’s easier

It’ s less error-prone

It can allow customization of the XML structure

17.

What Is Xml Binding Relationships?

Answer»

The relationships between the components INVOLVED in XML binding (data binding) are SHOWN below schema -> CLASSES XML -> schema Schema generates classes.

  1. Objects are instanceof classes.
  2. MARSHAL from objects to XML
  3. Unmarshall from XML to objects
  4. XML validates and conforms to Schema

The relationships between the components involved in XML binding (data binding) are shown below schema -> classes XML -> schema Schema generates classes.

18.

What Is Xml Binding?

Answer»

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:

used to generate the classes of the objects validation of object trees against the schema used to generate their classes

  • some constraints are ENFORCED while working with the objects
  • others are only enforced when validation is requested

Maps XML to in-memory objects according to a schema

Generates classes to represent XML elements:

Supports three primary operations:

includes validation of the XML against the schema:

used to generate the classes of the objects validation of object trees against the schema used to generate their classes