Top 18 Jaxb Interview Questions
Q1. Why Use Xml Binding?
It’s no longer vital
the whole thing that should be carried out with XML can be carried out with SAX and DOM
It’s simpler
don’t have to write as a great deal code
don’t need to learn SAX and/or DOM
It’ s less mistakes-inclined
all of the features of the schema are applied
don’ t ought to take into account to manually put into effect them
It can allow customization of the XML structure
unlike XMLEncoder and XMLDecoder within the java.Be package deal
Q2. 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>
Q3. What Are The Disadvantages/non-dreams Of Jaxb?
Standardize generated Java:
lessons generated with the aid of distinct JAXB implementations won't be well suited with each other
Preserve XML equivalence:
unmarshalling XML to items and marshalling again to XML may not bring about equal XML
Bind existing JavaBe to schemas:
can handiest marshal and unmarshal lessons generated by JAXB
can be delivered later
Schema evolution support:
can’ t adjust formerly generated code to help schema modifications
have to generated new code
Allow generated Java to get entry to:
XML factors/attributes now not defined in initial schema
Partial binding:
unmarshalling simplest a subset of an XML record breaks round tripping
Implement every feature of the schema language:
it’ s hard to put into effect all of XML Schema!
Support DTDs:
that specialize in XML Schema
DTDs were supported in an in advance version, but gained’ t be anymore
equipment for changing DTDs to XML Schemas exist
Q4. Discuss Customization Levels?
Customizations may be made at four levels
international:
described at “pinnacle stage” in a detail
applies to all schema factors inside the source schema and in all blanketed/imported schemas (recursively)
schema:
described at “pinnacle degree” in a element
applies to all schema elements inside the goal namespace of the source schema
definition:
defined in a type or worldwide announcement
applies to all schema factors that reference the type or worldwide statement
issue:
defined in a selected schema element or attribute assertion
applies only to it
Q5. What Is Xml Binding Relationships?
The relationships between the components worried in XML binding (facts binding) are shown underneath schema -> classes XML -> schema Schema generates training.
Objects are instanceof training.
Marshal from objects to XML
Unmarshall from XML to objects
XML validates and conforms to Schema
Q6. Explain The Syntax Of Customization?
Customizations may be laid out in
the XML Schema (our recognition)
a binding declarations XML record (not properly supported by means of RI but)
The XML Schema need to claim
the JAXB namespace and version
xmlns:jxb="http://java.Solar.Com/xml/ns/jaxb"
jxb:version="1.0">
Customization factors are positioned in annotation elements
<xsd:annotation>
<xsd:appinfo>
binding declarations
</xsd:appinfo>
</xsd:annotation>
Q7. How To Validate Java Objects?
The graph of Java objects can contain invalid statistics:
may want to arise whilst items created via unmarshalling are modified
ought to occur whilst objects are constituted of scratch
Use a Validator to validate the objects
Example:
Validator v = manufacturing unit.CreateValidator();
attempt
v.ValidateRoot(vehicles);
v.Validate(vehicle);
catch (ValidationException e)
// Handle the validation error defined by means of e.GetMessage().
Other Validator strategies:
boolean setEventHandler(ValidationEventHandler handler)
• handleEvent approach of ValidationEventHandler is referred to as
if validation errors are encountered
default handler terminates marshalling after first mistakes
go back true to maintain validating
return false to terminate with ValidationException
Pass an example of javax.Xml.Bind.Util.ValidationEventCollector (in jaxb-api.Jar) to setEventHandler to collect validation mistakes and question them later as opposed to handling them at some point of validation.
ValidationEventCollector vec =
new ValidationEventCollector();
v.SetEventHandler(vec);
v.Validate(vehicles);
ValidationEvent[] activities = vec.GetEvents();
Q8. Java Example/java Program To Set Object For Generating Xml?
Cars cars = manufacturing unit.CreateCars();
Car car = manufacturing unit.CreateCar();
car.SetColor("blue");
automobile.SetMake("Mazda");
automobile.SetModel("Miata");
automobile.SetYear(BigInteger.ValueOf(2012));
cars.GetCar().Upload(automobile);
automobile = factory.CreateCar();
car.SetColor("red");
vehicle.SetMake("Ford");
car.SetModel("Mustang II");
automobile.SetYear(BigInteger.ValueOf(2011));
automobiles.GetCar().Add(car);
Q9. 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>
Q10. What Are The Goals Of Jaxb?
Easy to apply:
require minimal XML expertise
don’ t require SAX/DOM know-how
Customizable:
can customize mapping of XML to Java
Portable:
can alternate JAXB implementation with out converting source code
Deliver quickly:
supply middle capability ASAP
Natural:
follow fashionable layout 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 call for:
validate objects with out requiring marshalling
Preserve object equivalence:
(round tripping)
marshalling items to XML and unmarshalling returned to items outcomes in equivalent objects
Q11. Java Code For Marshalling Java Objects Into Xml?
Example:
Marshaller m = manufacturing unit.CreateMarshaller();
m.SetProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
Writer fw = new FileWriter(“newCars.Xml”);
m.Marshal(automobiles, fw);
marshal technique accepts:
java.Io.OutputStream
java.Io.Writer
javax.Xml.Trform.Result
associated with XSLT
org.W3c.Dom.Node
associated with DOM
org.Xml.Sax.ContentHandler
related to SAX
• Other Marshaller techniques
boolean setEventHandler(ValidationEventHandler handler)
equal as use with Unmarshaller, however validation events
are brought for the duration of marshalling
void setProperty(String name, Object cost)
supported houses are
jaxb.Encoding – cost is a String
the encoding to use while marshalling; defaults to “UTF-eight”
jaxb.Formatted.Output – value is a Boolean
actual to output line breaks and indentation; fake to omit (the default)
jaxb.SchemaLocation – fee is a String
to specify xsi:schemaLocation attribute in generated XML
jaxb.NoNamespaceSchemaLocation – price is a String
to specify xsi:noNamespaceSchemaLocation attribute in generated XML
Q12. How To Unmarshall Xml Into Java Objects? Convert From Xml To Java Objects?
Example:
ObjectFactory manufacturing facility = new ObjectFactory();
Unmarshaller u = factory.CreateUnmarshaller();
Cars vehicles = (Cars) u.Unmarshal(new FileInputStream(“vehicles.Xml”));
unmarshal approach accepts:
java.Io.File
java.Io.InputStream
java.Net.URL
javax.Xml.Trform.Source
related to XSLT:
org.W3c.Dom.Node
related to DOM:
org.Xml.Sax.InputSource
associated with SAX:
• Other Unmarshaller techniques
void setValidating(boolean validating)
• real to enable validation at some stage in unmarshalling; false to disable (the default)
boolean setEventHandler(ValidationEventHandler handler)
• handleEvent technique of ValidationEventHandler is known as
if validation errors are encountered at some point of unmarshalling
• default handler terminates marshalling after first blunders
• return authentic to retain unmarshalling
• return false to terminate with UnmarshalExceptio
• see dialogue of ValidationEventCollector later
Q13. Explain Jaxb Use Cases?
Create/Read/Modify XML using Java
however with out the use of SAX or DOM
Validate person input:
the use of rules described in XML Schemas
Use XML-primarily based configuration files
get entry to their values
write tools that creates and modifies these documents
Q14. What Is Xml Binding?
Maps XML to in-reminiscence gadgets in step with a schema
Generates classes to represent XML factors:
so builders don’t ought to write them
the “binding compiler” does this
the training follow JavaBe assets get right of entry to conventions
Supports 3 number one operations:
marshalling a tree of gadgets into an XML report
unmarshalling an XML file right into a tree of objects
consists of validation of the XML towards the schema:
used to generate the instructions of the gadgets validation of item trees against the schema used to generate their training
a few constraints are enforced at the same time as working with the objects
others are only enforced whilst validation is requested
Q15. How To Generate Java From Xml Schema. Please Show The Example?
From command-line:
Windows: %JAXB_HOMEpercentbinxjc automobiles.Xsd
UNIX: %JAXB_HOME%/bin/xjc.Sh automobiles.Xsd
those write generated documents 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 “vehicle” complicated type
only describes get and set strategies for vehicle homes
Cars.Java:
interface representing “cars” international detail
extends CarsType and javax.Xml.Bind.Element (only a marker interface)
describes no additional methods
CarsType.Java:
interface representing nameless complex type described inside the “automobiles” global detail
offers approach to get series of Car gadgets (as a java.Util.List)
ObjectFactory.Java:
class used to create gadgets of the above interface sorts
extends DefaultJAXBContextImpl which extends JAXBContext
bgm.Ser:
a serialized item of kind com.Sun.Msv.Grammar.Trex.TREXGrammar
can’t locate any documentation in this - don’t recognise its cause
jaxb.Residences:
units a property that defines the magnificence used to create JAXBContext gadgets
com/withoutbook/cars/impl listing
CarImpl.Java:
magnificence that implements Car
corresponds to the “automobile” XML Schema complexType
CarsTypeImpl.Java:
magnificence that implements CarType
corresponds to the XML Schema anonymous kind in the “automobiles” detail
CarsImpl.Java:
elegance that extends CarsTypeImpl and implements Cars
corresponds to the “cars” XML Schema element
Q16. Explain Customizing Type Bindings?
Default bindings may be overridden:
at international scope
on case-via-case basis
Customizations include
names of generated package, instructions and techniques
approach return sorts
elegance property (field) kinds
which elements are bound to lessons, in place of being omitted
elegance belongings to which every characteristic and detail statement is sure
Q17. What Is The Syntax Of Schemabindings?
The syntax for the schemaBindings detail is
<jxb:schemaBindings>
<jxb:package [name="package-name"]>
<jxb:javadoc> ... Javadoc ... </jxb:javadoc>
</package>
<jxb:nameXmlTrform>
<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:nameXmlTrform>
</jxb:schemaBindings>
– each detail and attribute inside schemaBindings is non-obligatory
Q18. Discuss Global Bindings Attributes?
CollectionType:
“listed” (uses array and gives methods to get/set elements) or absolutely-qualified-java-elegance-name(have to put in force java.Util.List)
default is “java.Util.ArrayList”
enableFailFastCheck:
"genuine” or “fake” (default)
if proper, invalid assets values are said as quickly as they are set, as opposed to ready till validation is requested
no longer carried out but in RI
generateIsSetMethod:
“authentic” or “false” (default)
if authentic, generates isSet and unSet strategies for the assets
underscoreBinding
“asCharInWord” or “asWordSeparator” (default)
if “asWordSeparator” , underscores in XML names are eliminated and words are camel-cased to form Java call
for example, “gear_shift_knob” goes to “gearShiftKnob”
bindingStyle (was modelGroupAsClass):
“modelGroupBinding” or “elementBinding” (default)
choiceContentProperty:
“true” or “fake” (default)
lets in gadgets to maintain one in all some of belongings alternatives which may also each have a specific records type
enableJavaNamingConventions:
“genuine” (default) or “false”
fixedAttributeAsConstantProperty:
“true” or “fake” (default)
if authentic, “constant” attributes will be represented as constants
typesafeEnumBase:
“xsd:string” , “xsd:decimal” , “xsd:float” , “xsd:double” or “xsd:NCName” (default)
defines field kind used to represent enumerated values in generated typesafe enum class
typesafeEnumMemberName:
“generateName” or “generateError” (default)
specifies what to do if an enumerated fee can not be mapped to a valid Java identifier
“generateName” generates names within the form VALUE_#
“generateError” reviews an mistakes

