SlideShare a Scribd company logo
Jan 21, 2016
JAXB
Java Architecture for XML Binding
What is JAXB?
īŽ JAXB is Java Architecture for XML Binding
īŽ SAX and DOM are generic XML parsers
īŽ They will parse any well-structured XML
īŽ JAXB creates a parser that is specific to your DTD
īŽ A JAXB parser will parse only valid XML (as defined by your
DTD)
īŽ DOM and JAXB both produce a tree in memory
īŽ DOM produces a generic tree; everything is a Node
īŽ JAXB produces a tree of Objects with names and attributes as
described by your DTD
Advantages and disadvantages
īŽ Advantages:
īŽ JAXB requires a DTD
īŽ
Using JAXB ensures the validity of your XML
īŽ A JAXB parser is actually faster than a generic SAX parser
īŽ A tree created by JAXB is smaller than a DOM tree
īŽ It’s much easier to use a JAXB tree for application-specific code
īŽ You can modify the tree and save it as XML
īŽ Disadvantages:
īŽ JAXB requires a DTD
īŽ
Hence, you cannot use JAXB to process generic XML (for example, if
you are writing an XML editor or other tool)
īŽ You must do additional work up front to tell JAXB what kind of tree
you want it to construct
īŽ
But this more than pays for itself by simplifying your application
īŽ JAXB is new: Version 1.0 dates from Q4 (fourth quarter) 2002
How JAXB works
īŽ JAXB takes as input two files: your DTD and a binding
schema (which you also write)
īŽ A binding schema is an XML document written in a “binding
language” defined by JAXB (with extension .xjs)
īŽ A binding schema is used to customize the JAXB output
īŽ Your binding schema can be very simple or quite complex
īŽ JAXB produces as output Java source code which you
compile and add to your program
īŽ Your program will uses the specific classes generated by JAXB
īŽ Your program can then read and write XML files
īŽ JAXB also provides an API for working directly with XML
īŽ Some examples in this lecture are taken from the JAXB User’s guide,
http://java.sun.com/xml/jaxb/docs.html
A first example
īŽ The DTD: <!ELEMENT book (title, author, chapter+) >
<!ELEMENT title (#PCDATA) >
<!ELEMENT author (#PCDATA)>
<!ELEMENT chapter (#PCDATA) >
īŽ The schema: <xml-java-binding-schema>
<element name="book" type="class" root="true" />
</xml-java-binding-schema>
īŽ The results: public Book(); // constructor
public String getTitle();
public void setTitle(String x);
public String getAuthor();
public void setAuthor(String x);
public List getChapter();
public void deleteChapter();
public void emptyChapter();
Note 1: In these slides
we only show the class
outline, but JAXB
creates a complete
class for you
Note 2: JAXB constructs
names based on yours,
with good capitalization
style
Adding complexity
īŽ Adding a choice can reduce the usefulness of the parser
īŽ <!ELEMENT book (title, author, (prologue | preface), chapter+)>
<!ELEMENT prologue (#PCDATA) >
<!ELEMENT preface (#PCDATA) >
īŽ With the same binding schema, this gives:
īŽ
public Book();
public List getContent();
public void deleteContent();
public void emptyContent();
īŽ An improved binding schema can give better results
Improving the binding schema
īŽ <xml-java-binding-schema>
<element name="book" type="class" root="true">
<content>
<element-ref name="title" />
<element-ref name="author” />
<choice property="prologue-or-preface" />
</content>
</element>
</xml-java-binding-schema>
īŽ Result is same as the original, plus methods for the choice:
īŽ public Book(); // constructor
. . .
public void emptyChapter();
public MarshallableObject getPrologueOrPreface();
public void setPrologueOrPreface(MarshallableObject x);
Marshalling
īŽ marshal, v.t.: to place or arrange in order
īŽ marshalling: the process of producing an XML
document from Java objects
īŽ unmarshalling: the process of producing a content tree
from an XML document
īŽ JAXB only allows you to unmarshal valid XML
documents
īŽ JAXB only allows you to martial valid content trees
into XML
Limitations of JAXB
īŽ JAXB only supports DTDs and a subset of XML
Schemas
īŽ Later versions may support more schema languages
īŽ JAXB does not support the following legal DTD
constructs:
īŽ Internal subsets
īŽ NOTATIONs
īŽ ENTITY and ENTITIES
īŽ Enumerated NOTATION types
A minimal binding schema
īŽ A JAXB binding schema is itself in XML
īŽ Start with: <xml-java-binding-schema version="1.0ea">
īŽ The version is optional
īŽ “ea” stands for “early access,” that is, not yet released
īŽ Put in:
<element name="rootName" type="class" root="true" />
for each possible root element
īŽ An XML document can have only one root
īŽ However, the DTD does not say what that root must be
īŽ Any top-level element defined by the DTD may be a root
īŽ The value of name must match exactly with the name in the DTD
īŽ End with: </xml-java-binding-schema>
More complex schemata
īŽ JAXB requires that you supply a binding schema
īŽ As noted on the previous slide, this would be
<xml-java-binding-schema version="1.0ea">
<element name="rootName" type="class" root="true" />
</xml-java-binding-schema>
īŽ With this binding schema, JAXB uses its default rule
set to generate your “bindings”
īŽ A binding is an association between an XML element and
the Java code used to process that element
īŽ By adding to this schema, you can customize the
bindings and thus the generated Java code
Default bindings, I
īŽ A “simple element” is one that has no attributes and only
character contents:
īŽ <!ELEMENT elementName (#PCDATA) >
īŽ For simple elements, JAXB assumes:
<element name="elementName" type="value"/>
īŽ JAXB will treat this element as an instance variable of the class
for its enclosing element
īŽ This is the default binding, that is, this is what JAXB will assume
unless you tell it otherwise
īŽ
For example, you could write this yourself, but set type="class"
īŽ For simple elements, JAXB will generate these methods in the
class of the enclosing element:
void setElementName(String x);
String getElementName();
īŽ We will see later how to convert the #PCDATA into some type
other than String
Default bindings, II
īŽ If an element is not simple, JAXB will treat it as a class
īŽ Attributes and simple subelements are treated as instance variables
īŽ DTD: <!ELEMENT elementName (subElement1, subElement2) >
<!ATTLIST elementName attributeName CDATA #IMPLIED>
īŽ Binding: <element name="elementName" type="class">
<attribute name="attributeName"/>
<content>
<element-ref name="subElement1" /> <!-- simple element -->
<element-ref name="subElement2" /> <!-- complex element -->
</content>
</element>
īŽ Java: class ElementName extends MarshallableObject {
void setAttributeName1(String x);
String getAttributeName1();
String getSubElement1();
void setSubElement1(String x);
// Non-simple subElement2 is described on the next slide
Default bindings, III
īŽ If an element contains a subelement that is defined by a
class, the code generated will be different
īŽ <element name="elementName" type="class">
<content>
<element-ref name="subElement2" />
<!-- Note that "element-ref" means this is a reference to
an
element that is defined elsewhere, not the element
itself -->
</content>
</element>
īŽ Results in:
class ElementName extends MarshallableObject {
SubElement2 getSubElement2();
void setSubElement2(SubElement2 x);
...}
īŽ Elsewhere, the DTD definition for subElement2 will result in:
class SubElement2 extends MarshallableObject { ... }
Default bindings, IV
īŽ A simple sequence is just a list of contents, in order, with no
+ or * repetitions
īŽ Example: <!ELEMENT html (head, body) >
īŽ For an element defined with a simple sequence, setters and getters are
created for each item in the sequence
īŽ If an element’s definition isn’t simple, or if it contains
repetitions, JAXB basically “gives up” and says “it’s got
some kind of content, but I don’t know what”
īŽ Example: <!ELEMENT book (title, forward, chapter*)>
īŽ Result:
public Book(); // constructor
public List getContent(); // "general content"--not too useful!
public void deleteContent();
public void emptyContent();
Customizing the binding schema
īŽ You won’t actually see these default bindings anywhere--
they are just assumed
īŽ If a default binding is OK with you, don’t do anything
īŽ If you don’t like a default binding, just write your own
īŽ Here’s the minimal binding you must write:
<xml-java-binding-schema>
<element name="rootElement" type="class" root="true" />
</xml-java-binding-schema>
īŽ Start by “opening up” the root element:
<xml-java-binding-schema>
<element name="rootElement" type="class" root="true" >
</element>
</xml-java-binding-schema>
īŽ Now you have somewhere to put your customizations
Primitive attributes
īŽ By default, attributes are assumed to be Strings
īŽ <!ATTLIST someElement someAttribute CDATA #IMPLIED>
īŽ class SomeElement extends MarshallableObject {
void setSomeAttribute(String x);
String getSomeAttribute();
īŽ You can define your own binding and use the convert attribute
to force the defined attribute to be a primitive, such as an int:
īŽ <element name="someElement " type="class" >
<attribute name="someAttribute" convert="int" />
</element>
īŽ class SomeElement extends MarshallableObject {
void setSomeAttribute(int x);
int getSomeAttribute();
Conversions to Objects, I
īŽ At the top level (within <xml-binding-schema>), add
a conversion declaration, such as:
īŽ <conversion name="BigDecimal" type="java.math.BigDecimal" />
īŽ
name is used in the binding schema
īŽ
type is the actual class to be used
īŽ Add a convert attribute where you need it:
īŽ <element name="name" type="value" convert="BigDecimal" />
īŽ The result should be:
īŽ public java.math.BigDecimal getName();
public void setName(java.math.BigDecimal x);
īŽ This works for BigDecimal because it has a
constructor that takes a String as its argument
Conversions to Objects, II
īŽ There is a constructor for Date that takes a String as its
one argument, but this constructor is deprecated
īŽ This is because there are many ways to write dates
īŽ For an object like this, you need to supply methods to “parse”
and “print”
īŽ <conversion name="MyDate" type="java.util.Date”
parse="MyDate.parseDate" print="MyDate.printDate"/>
īŽ Your class, MyDate, would extend Date and provide
parseDate and printDate methods
Creating enumerations
īŽ <!ATTLIST shirt size (small | medium | large) #IMPLIED> defines an attribute
of shirt that can take on one of a predefined set of values
īŽ A typesafe enum is a class whose instances are a predefined set of values
īŽ To create a typesafe enum for size:
īŽ <enumeration name="shirtSize" members="small medium large">
īŽ <element name="shirt" ...>
<attribute name="size" convert="shirtSize" />
</element>
īŽ You get:
īŽ public final class ShirtSize {
public final static ShirtSize SMALL;
public final static ShirtSize MEDIUM;
public final static ShirtSize LARGE;
public static ShirtSize parse(String x);
public String toString();
}
Content models
īŽ The <content> tag describes one of two kinds of content
models:
īŽ A general-content property binds a single property
īŽ
You’ve seen this before:
<content property="my-content" />
īŽ
Gives: public List getMyContent();
public void deleteMyContent();
public void emptyMyContent();
īŽ A model-based content property can contain four types of
declarations:
īŽ
element-ref says that this element contains another element
īŽ
choice says that there are alternative contents
īŽ
sequence says that contents must be in a particular order
īŽ
rest can be used to specify any kind of content
Using JAXB
īŽ JAXB is not currently a part of the standard Java distributions
īŽ The steps involved in using JAXB are:
īŽ Download, install, and configure JAXB
īŽ Write a JAXB schema to describe the bindings you want for your XML
īŽ Use JAXB to read the JAXB schema and the XML DTD (or XML
Schema) and produce Java code
īŽ Add the Java code to your program and compile it
īŽ Use the resultant program to:
īŽ
Read and validate XML input files
īŽ
Modify the XML tree
īŽ
Optionally validate and output the modified XML
īŽ Note: Validation is optional and can be performed during unmarshalling
or any time thereafter
The End

More Related Content

What's hot

Delegates and events
Delegates and eventsDelegates and events
Delegates and events
Iblesoft
 
Js ppt
Js pptJs ppt
Js ppt
Rakhi Thota
 
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Simplilearn
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
æ´Ē 随发
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
sahilrk911
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
Applets in java
Applets in javaApplets in java
Applets in java
Wani Zahoor
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
Riccardo Cardin
 
File handling
File handlingFile handling
File handling
priya_trehan
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
ejlp12
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
Prem Kumar Badri
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
Madishetty Prathibha
 
JDBC
JDBCJDBC
Struts framework
Struts frameworkStruts framework
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Beyond syllabus for web technology
Beyond syllabus for web technologyBeyond syllabus for web technology
Beyond syllabus for web technology
Durga Bhargavi Yarrabally
 

What's hot (20)

Delegates and events
Delegates and eventsDelegates and events
Delegates and events
 
Js ppt
Js pptJs ppt
Js ppt
 
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
Abstract Class In Java | Java Abstract Class Tutorial | Java Tutorial For Beg...
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Bridge Design Pattern
Bridge Design PatternBridge Design Pattern
Bridge Design Pattern
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
File handling
File handlingFile handling
File handling
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Java EE Introduction
Java EE IntroductionJava EE Introduction
Java EE Introduction
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
 
Structure of java program diff c- cpp and java
Structure of java program  diff c- cpp and javaStructure of java program  diff c- cpp and java
Structure of java program diff c- cpp and java
 
JDBC
JDBCJDBC
JDBC
 
Struts framework
Struts frameworkStruts framework
Struts framework
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
 
Beyond syllabus for web technology
Beyond syllabus for web technologyBeyond syllabus for web technology
Beyond syllabus for web technology
 

Viewers also liked

Xml material
Xml materialXml material
Xml material
prathap kumar
 
Displaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSLDisplaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSL
BÃŦnh Tráģng Án
 
XSLT
XSLTXSLT
Dtd
DtdDtd
XML Schema
XML SchemaXML Schema
XML Schema
Kumar
 
XSLT
XSLTXSLT
XSLT
rpoplai
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
yht4ever
 
Template Design for SAGD
Template Design for SAGDTemplate Design for SAGD
Template Design for SAGD
AVEVA Group plc
 

Viewers also liked (8)

Xml material
Xml materialXml material
Xml material
 
Displaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSLDisplaying XML Documents Using CSS and XSL
Displaying XML Documents Using CSS and XSL
 
XSLT
XSLTXSLT
XSLT
 
Dtd
DtdDtd
Dtd
 
XML Schema
XML SchemaXML Schema
XML Schema
 
XSLT
XSLTXSLT
XSLT
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
Template Design for SAGD
Template Design for SAGDTemplate Design for SAGD
Template Design for SAGD
 

Similar to Jaxb

XML
XMLXML
Ch23
Ch23Ch23
Ch23
preetamju
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_java
ardnetij
 
Xml session
Xml sessionXml session
Xml session
Farag Zakaria
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
Malintha Adikari
 
advDBMS_XML.pptx
advDBMS_XML.pptxadvDBMS_XML.pptx
advDBMS_XML.pptx
IreneGetzi
 
Xml Java
Xml JavaXml Java
Xml Java
cbee48
 
unit_5_XML data integration database management
unit_5_XML data integration database managementunit_5_XML data integration database management
unit_5_XML data integration database management
sathiyabcsbs
 
DATA INTEGRATION (Gaining Access to Diverse Data).ppt
DATA INTEGRATION (Gaining Access to Diverse Data).pptDATA INTEGRATION (Gaining Access to Diverse Data).ppt
DATA INTEGRATION (Gaining Access to Diverse Data).ppt
careerPointBasti
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
vishal choudhary
 
Jdom how it works & how it opened the java process
Jdom how it works & how it opened the java processJdom how it works & how it opened the java process
Jdom how it works & how it opened the java process
Hicham QAISSI
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
Aravindharamanan S
 
Processing XML
Processing XMLProcessing XML
Processing XML
Ólafur Andri Ragnarsson
 
Using schemas in parsing xml part 1
Using schemas in parsing xml part 1Using schemas in parsing xml part 1
Using schemas in parsing xml part 1
Alex Fernandez
 
Service Oriented Architecture -Unit II - Modeling databases in xml
Service Oriented Architecture -Unit II - Modeling databases in xml Service Oriented Architecture -Unit II - Modeling databases in xml
Service Oriented Architecture -Unit II - Modeling databases in xml
Roselin Mary S
 
Xml writers
Xml writersXml writers
Xml writers
Raghu nath
 
XML-Javascript
XML-JavascriptXML-Javascript
XML-Javascript
tutorialsruby
 
XML-Javascript
XML-JavascriptXML-Javascript
XML-Javascript
tutorialsruby
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
DrMeenakshiS
 
Xsd
XsdXsd

Similar to Jaxb (20)

XML
XMLXML
XML
 
Ch23
Ch23Ch23
Ch23
 
Ch23 xml processing_with_java
Ch23 xml processing_with_javaCh23 xml processing_with_java
Ch23 xml processing_with_java
 
Xml session
Xml sessionXml session
Xml session
 
XML parsing using jaxb
XML parsing using jaxbXML parsing using jaxb
XML parsing using jaxb
 
advDBMS_XML.pptx
advDBMS_XML.pptxadvDBMS_XML.pptx
advDBMS_XML.pptx
 
Xml Java
Xml JavaXml Java
Xml Java
 
unit_5_XML data integration database management
unit_5_XML data integration database managementunit_5_XML data integration database management
unit_5_XML data integration database management
 
DATA INTEGRATION (Gaining Access to Diverse Data).ppt
DATA INTEGRATION (Gaining Access to Diverse Data).pptDATA INTEGRATION (Gaining Access to Diverse Data).ppt
DATA INTEGRATION (Gaining Access to Diverse Data).ppt
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Jdom how it works & how it opened the java process
Jdom how it works & how it opened the java processJdom how it works & how it opened the java process
Jdom how it works & how it opened the java process
 
Tomcat + other things
Tomcat + other thingsTomcat + other things
Tomcat + other things
 
Processing XML
Processing XMLProcessing XML
Processing XML
 
Using schemas in parsing xml part 1
Using schemas in parsing xml part 1Using schemas in parsing xml part 1
Using schemas in parsing xml part 1
 
Service Oriented Architecture -Unit II - Modeling databases in xml
Service Oriented Architecture -Unit II - Modeling databases in xml Service Oriented Architecture -Unit II - Modeling databases in xml
Service Oriented Architecture -Unit II - Modeling databases in xml
 
Xml writers
Xml writersXml writers
Xml writers
 
XML-Javascript
XML-JavascriptXML-Javascript
XML-Javascript
 
XML-Javascript
XML-JavascriptXML-Javascript
XML-Javascript
 
jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Xsd
XsdXsd
Xsd
 

More from Manav Prasad

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
Manav Prasad
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
Manav Prasad
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
Manav Prasad
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
Manav Prasad
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
Manav Prasad
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
Manav Prasad
 
Jpa
JpaJpa
Spring introduction
Spring introductionSpring introduction
Spring introduction
Manav Prasad
 
Json
Json Json
Json
Manav Prasad
 
The spring framework
The spring frameworkThe spring framework
The spring framework
Manav Prasad
 
Rest introduction
Rest introductionRest introduction
Rest introduction
Manav Prasad
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
Manav Prasad
 
Junit
JunitJunit
Junit
Manav Prasad
 
Xml parsers
Xml parsersXml parsers
Xml parsers
Manav Prasad
 
Xpath
XpathXpath
Xpath
Manav Prasad
 
Xslt
XsltXslt
Xslt
Manav Prasad
 
Xhtml
XhtmlXhtml
Xhtml
Manav Prasad
 
Css
CssCss
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
Manav Prasad
 
Ajax
AjaxAjax
Ajax
Manav Prasad
 

More from Manav Prasad (20)

Experience with mulesoft
Experience with mulesoftExperience with mulesoft
Experience with mulesoft
 
Mulesoftconnectors
MulesoftconnectorsMulesoftconnectors
Mulesoftconnectors
 
Mule and web services
Mule and web servicesMule and web services
Mule and web services
 
Mulesoft cloudhub
Mulesoft cloudhubMulesoft cloudhub
Mulesoft cloudhub
 
Perl tutorial
Perl tutorialPerl tutorial
Perl tutorial
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Jpa
JpaJpa
Jpa
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Json
Json Json
Json
 
The spring framework
The spring frameworkThe spring framework
The spring framework
 
Rest introduction
Rest introductionRest introduction
Rest introduction
 
Exceptions in java
Exceptions in javaExceptions in java
Exceptions in java
 
Junit
JunitJunit
Junit
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
Xpath
XpathXpath
Xpath
 
Xslt
XsltXslt
Xslt
 
Xhtml
XhtmlXhtml
Xhtml
 
Css
CssCss
Css
 
Introduction to html5
Introduction to html5Introduction to html5
Introduction to html5
 
Ajax
AjaxAjax
Ajax
 

Recently uploaded

Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
Fwdays
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo GÃŗmez Abajo
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
Vadym Kazulkin
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
DanBrown980551
 

Recently uploaded (20)

Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin..."$10 thousand per minute of downtime: architecture, queues, streaming and fin...
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024High performance Serverless Java on AWS- GoTo Amsterdam 2024
High performance Serverless Java on AWS- GoTo Amsterdam 2024
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
 

Jaxb

  • 1. Jan 21, 2016 JAXB Java Architecture for XML Binding
  • 2. What is JAXB? īŽ JAXB is Java Architecture for XML Binding īŽ SAX and DOM are generic XML parsers īŽ They will parse any well-structured XML īŽ JAXB creates a parser that is specific to your DTD īŽ A JAXB parser will parse only valid XML (as defined by your DTD) īŽ DOM and JAXB both produce a tree in memory īŽ DOM produces a generic tree; everything is a Node īŽ JAXB produces a tree of Objects with names and attributes as described by your DTD
  • 3. Advantages and disadvantages īŽ Advantages: īŽ JAXB requires a DTD īŽ Using JAXB ensures the validity of your XML īŽ A JAXB parser is actually faster than a generic SAX parser īŽ A tree created by JAXB is smaller than a DOM tree īŽ It’s much easier to use a JAXB tree for application-specific code īŽ You can modify the tree and save it as XML īŽ Disadvantages: īŽ JAXB requires a DTD īŽ Hence, you cannot use JAXB to process generic XML (for example, if you are writing an XML editor or other tool) īŽ You must do additional work up front to tell JAXB what kind of tree you want it to construct īŽ But this more than pays for itself by simplifying your application īŽ JAXB is new: Version 1.0 dates from Q4 (fourth quarter) 2002
  • 4. How JAXB works īŽ JAXB takes as input two files: your DTD and a binding schema (which you also write) īŽ A binding schema is an XML document written in a “binding language” defined by JAXB (with extension .xjs) īŽ A binding schema is used to customize the JAXB output īŽ Your binding schema can be very simple or quite complex īŽ JAXB produces as output Java source code which you compile and add to your program īŽ Your program will uses the specific classes generated by JAXB īŽ Your program can then read and write XML files īŽ JAXB also provides an API for working directly with XML īŽ Some examples in this lecture are taken from the JAXB User’s guide, http://java.sun.com/xml/jaxb/docs.html
  • 5. A first example īŽ The DTD: <!ELEMENT book (title, author, chapter+) > <!ELEMENT title (#PCDATA) > <!ELEMENT author (#PCDATA)> <!ELEMENT chapter (#PCDATA) > īŽ The schema: <xml-java-binding-schema> <element name="book" type="class" root="true" /> </xml-java-binding-schema> īŽ The results: public Book(); // constructor public String getTitle(); public void setTitle(String x); public String getAuthor(); public void setAuthor(String x); public List getChapter(); public void deleteChapter(); public void emptyChapter(); Note 1: In these slides we only show the class outline, but JAXB creates a complete class for you Note 2: JAXB constructs names based on yours, with good capitalization style
  • 6. Adding complexity īŽ Adding a choice can reduce the usefulness of the parser īŽ <!ELEMENT book (title, author, (prologue | preface), chapter+)> <!ELEMENT prologue (#PCDATA) > <!ELEMENT preface (#PCDATA) > īŽ With the same binding schema, this gives: īŽ public Book(); public List getContent(); public void deleteContent(); public void emptyContent(); īŽ An improved binding schema can give better results
  • 7. Improving the binding schema īŽ <xml-java-binding-schema> <element name="book" type="class" root="true"> <content> <element-ref name="title" /> <element-ref name="author” /> <choice property="prologue-or-preface" /> </content> </element> </xml-java-binding-schema> īŽ Result is same as the original, plus methods for the choice: īŽ public Book(); // constructor . . . public void emptyChapter(); public MarshallableObject getPrologueOrPreface(); public void setPrologueOrPreface(MarshallableObject x);
  • 8. Marshalling īŽ marshal, v.t.: to place or arrange in order īŽ marshalling: the process of producing an XML document from Java objects īŽ unmarshalling: the process of producing a content tree from an XML document īŽ JAXB only allows you to unmarshal valid XML documents īŽ JAXB only allows you to martial valid content trees into XML
  • 9. Limitations of JAXB īŽ JAXB only supports DTDs and a subset of XML Schemas īŽ Later versions may support more schema languages īŽ JAXB does not support the following legal DTD constructs: īŽ Internal subsets īŽ NOTATIONs īŽ ENTITY and ENTITIES īŽ Enumerated NOTATION types
  • 10. A minimal binding schema īŽ A JAXB binding schema is itself in XML īŽ Start with: <xml-java-binding-schema version="1.0ea"> īŽ The version is optional īŽ “ea” stands for “early access,” that is, not yet released īŽ Put in: <element name="rootName" type="class" root="true" /> for each possible root element īŽ An XML document can have only one root īŽ However, the DTD does not say what that root must be īŽ Any top-level element defined by the DTD may be a root īŽ The value of name must match exactly with the name in the DTD īŽ End with: </xml-java-binding-schema>
  • 11. More complex schemata īŽ JAXB requires that you supply a binding schema īŽ As noted on the previous slide, this would be <xml-java-binding-schema version="1.0ea"> <element name="rootName" type="class" root="true" /> </xml-java-binding-schema> īŽ With this binding schema, JAXB uses its default rule set to generate your “bindings” īŽ A binding is an association between an XML element and the Java code used to process that element īŽ By adding to this schema, you can customize the bindings and thus the generated Java code
  • 12. Default bindings, I īŽ A “simple element” is one that has no attributes and only character contents: īŽ <!ELEMENT elementName (#PCDATA) > īŽ For simple elements, JAXB assumes: <element name="elementName" type="value"/> īŽ JAXB will treat this element as an instance variable of the class for its enclosing element īŽ This is the default binding, that is, this is what JAXB will assume unless you tell it otherwise īŽ For example, you could write this yourself, but set type="class" īŽ For simple elements, JAXB will generate these methods in the class of the enclosing element: void setElementName(String x); String getElementName(); īŽ We will see later how to convert the #PCDATA into some type other than String
  • 13. Default bindings, II īŽ If an element is not simple, JAXB will treat it as a class īŽ Attributes and simple subelements are treated as instance variables īŽ DTD: <!ELEMENT elementName (subElement1, subElement2) > <!ATTLIST elementName attributeName CDATA #IMPLIED> īŽ Binding: <element name="elementName" type="class"> <attribute name="attributeName"/> <content> <element-ref name="subElement1" /> <!-- simple element --> <element-ref name="subElement2" /> <!-- complex element --> </content> </element> īŽ Java: class ElementName extends MarshallableObject { void setAttributeName1(String x); String getAttributeName1(); String getSubElement1(); void setSubElement1(String x); // Non-simple subElement2 is described on the next slide
  • 14. Default bindings, III īŽ If an element contains a subelement that is defined by a class, the code generated will be different īŽ <element name="elementName" type="class"> <content> <element-ref name="subElement2" /> <!-- Note that "element-ref" means this is a reference to an element that is defined elsewhere, not the element itself --> </content> </element> īŽ Results in: class ElementName extends MarshallableObject { SubElement2 getSubElement2(); void setSubElement2(SubElement2 x); ...} īŽ Elsewhere, the DTD definition for subElement2 will result in: class SubElement2 extends MarshallableObject { ... }
  • 15. Default bindings, IV īŽ A simple sequence is just a list of contents, in order, with no + or * repetitions īŽ Example: <!ELEMENT html (head, body) > īŽ For an element defined with a simple sequence, setters and getters are created for each item in the sequence īŽ If an element’s definition isn’t simple, or if it contains repetitions, JAXB basically “gives up” and says “it’s got some kind of content, but I don’t know what” īŽ Example: <!ELEMENT book (title, forward, chapter*)> īŽ Result: public Book(); // constructor public List getContent(); // "general content"--not too useful! public void deleteContent(); public void emptyContent();
  • 16. Customizing the binding schema īŽ You won’t actually see these default bindings anywhere-- they are just assumed īŽ If a default binding is OK with you, don’t do anything īŽ If you don’t like a default binding, just write your own īŽ Here’s the minimal binding you must write: <xml-java-binding-schema> <element name="rootElement" type="class" root="true" /> </xml-java-binding-schema> īŽ Start by “opening up” the root element: <xml-java-binding-schema> <element name="rootElement" type="class" root="true" > </element> </xml-java-binding-schema> īŽ Now you have somewhere to put your customizations
  • 17. Primitive attributes īŽ By default, attributes are assumed to be Strings īŽ <!ATTLIST someElement someAttribute CDATA #IMPLIED> īŽ class SomeElement extends MarshallableObject { void setSomeAttribute(String x); String getSomeAttribute(); īŽ You can define your own binding and use the convert attribute to force the defined attribute to be a primitive, such as an int: īŽ <element name="someElement " type="class" > <attribute name="someAttribute" convert="int" /> </element> īŽ class SomeElement extends MarshallableObject { void setSomeAttribute(int x); int getSomeAttribute();
  • 18. Conversions to Objects, I īŽ At the top level (within <xml-binding-schema>), add a conversion declaration, such as: īŽ <conversion name="BigDecimal" type="java.math.BigDecimal" /> īŽ name is used in the binding schema īŽ type is the actual class to be used īŽ Add a convert attribute where you need it: īŽ <element name="name" type="value" convert="BigDecimal" /> īŽ The result should be: īŽ public java.math.BigDecimal getName(); public void setName(java.math.BigDecimal x); īŽ This works for BigDecimal because it has a constructor that takes a String as its argument
  • 19. Conversions to Objects, II īŽ There is a constructor for Date that takes a String as its one argument, but this constructor is deprecated īŽ This is because there are many ways to write dates īŽ For an object like this, you need to supply methods to “parse” and “print” īŽ <conversion name="MyDate" type="java.util.Date” parse="MyDate.parseDate" print="MyDate.printDate"/> īŽ Your class, MyDate, would extend Date and provide parseDate and printDate methods
  • 20. Creating enumerations īŽ <!ATTLIST shirt size (small | medium | large) #IMPLIED> defines an attribute of shirt that can take on one of a predefined set of values īŽ A typesafe enum is a class whose instances are a predefined set of values īŽ To create a typesafe enum for size: īŽ <enumeration name="shirtSize" members="small medium large"> īŽ <element name="shirt" ...> <attribute name="size" convert="shirtSize" /> </element> īŽ You get: īŽ public final class ShirtSize { public final static ShirtSize SMALL; public final static ShirtSize MEDIUM; public final static ShirtSize LARGE; public static ShirtSize parse(String x); public String toString(); }
  • 21. Content models īŽ The <content> tag describes one of two kinds of content models: īŽ A general-content property binds a single property īŽ You’ve seen this before: <content property="my-content" /> īŽ Gives: public List getMyContent(); public void deleteMyContent(); public void emptyMyContent(); īŽ A model-based content property can contain four types of declarations: īŽ element-ref says that this element contains another element īŽ choice says that there are alternative contents īŽ sequence says that contents must be in a particular order īŽ rest can be used to specify any kind of content
  • 22. Using JAXB īŽ JAXB is not currently a part of the standard Java distributions īŽ The steps involved in using JAXB are: īŽ Download, install, and configure JAXB īŽ Write a JAXB schema to describe the bindings you want for your XML īŽ Use JAXB to read the JAXB schema and the XML DTD (or XML Schema) and produce Java code īŽ Add the Java code to your program and compile it īŽ Use the resultant program to: īŽ Read and validate XML input files īŽ Modify the XML tree īŽ Optionally validate and output the modified XML īŽ Note: Validation is optional and can be performed during unmarshalling or any time thereafter

Editor's Notes

  1. This whole talk is based on http://java.sun.com/xml/jaxb/docs.html, which is actually pretty badly written; it uses many examples but the discussions seriously lack precision. I should go to the spec or find another description somewhere, and check these slides carefully.