"Welcome To Ashok IT" "Spring Boot & Microservices" Topic : Data Formats(XML) Date : 19/12/2023 (Session - 88) _____________________________________________________________________________________________________________________________ Yesterday Session ================= * We discussed about Rest Principles & Importance of Http Protocal & HttpRequestHeader Format Today Session ============= XML === * XML Stands for "Extensible Markup Language". * XML governed by W3C. * The intial version of XML is 1.0 & Current version of XML is also 1.0. * XML is used to store & Transfer the data. * XML is an Interoperable(Platform Independent,Language Independent). * Every XML tag should have opening & Corresponding closing tag mandatorly. * We can validate the XML document simply by opening in browser window and If we are able to see the xml content as tree structure in browser indicates "Valid XML" otherwise "Not a Valid XML". * Every XML Contains only one element. * In XML we can have below types of elements 1) Simple element 2) Compound element * If the element contains data then it is called "Simple Element" Example ======= 101 Mahesh * If the XML element contains child XMl elements then it is called "Compound Element" Example =======
mahesh mahesh.ashokit@gmail.com
* In order to convert the Java Object into XML content (or) XML content into Java Object as Java Programmer we need to apply "Marshalling & Un-Marshalling" * Converting from Java Object into XML Content called "Marshalling". * Converting from XML Content into Java Object called "Un-Marshalling". * To Perform the Marshalling & Unmarshalling we need to use library "JAXB API" (Jakarta XML Binding). * Using JAXB API we will perform two kinds of operations 1) One Time Operation 2) Run Time Operation One Time Operation ================== * The Process of creating binding classes is called One time operation. * The Java Class which is representing XML structure is called Binding Class. Run Time Operation ================== * Performing the Marshalling & Un-Marshalling Operations. Examples ======== Customer c = new Customer(); XML c.setId(123); >>>>>>>> 123 c.setName("Mahesh"); Mahesh c.setLocation("Hyderabad"); Hyderabad Maven dependencies for XML API =============================== jakarta.xml.bind jakarta.xml.bind-api 4.0.0 com.sun.xml.bind jaxb-impl 4.0.1 runtime Example Application =================== Customer.java ============= package com.ashokit; import java.util.List; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlElementWrapper; import jakarta.xml.bind.annotation.XmlRootElement; import jakarta.xml.bind.annotation.XmlType; @XmlRootElement //root element to be represent in xml file @XmlAccessorType(XmlAccessType.FIELD) //performing the marshalling process at field level @XmlType(propOrder = {"name","id","location","order"}) //marhsalling ordering public class Customer { @XmlElement(name="customerId")//property name in marshalling process private Integer id; @XmlElement(name="customerName")//property name in marshalling process private String name; @XmlElement(name="customerLocation")//property name in marshalling process private String location; @XmlElementWrapper(name = "customerOrdersList") //wrapping orders into ordersList @XmlElement(name="customerOrder")//property name in marshalling process private List order; public Customer() { } public Customer(Integer id, String name, String location,List order) { super(); this.id = id; this.name = name; this.location = location; this.order = order; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public void setOrder(List order) { this.order = order; } public List getOrder() { return order; } @Override public String toString() { return "Customer [id=" + id + ", name=" + name + ", location=" + location + "]"; } } Order.java ========== package com.ashokit; import jakarta.xml.bind.annotation.XmlAccessType; import jakarta.xml.bind.annotation.XmlAccessorType; import jakarta.xml.bind.annotation.XmlElement; import jakarta.xml.bind.annotation.XmlRootElement; @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Order { @XmlElement(name="customerOrderId") private Integer orderId; @XmlElement(name="customerBillAmount") private double billAmount; public Order() { } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public double getBillAmount() { return billAmount; } public void setBillAmount(double billAmount) { this.billAmount = billAmount; } public Order(Integer orderId, double billAmount) { super(); this.orderId = orderId; this.billAmount = billAmount; } } XmlClient.java ============== package com.ashokit; import java.util.Arrays; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Marshaller; public class XmlClient { public static void main(String[] args) throws JAXBException { Order order = new Order(345,2500); Order order1 = new Order(645,3500); //Java Object is ready having data Customer c = new Customer(123,"Mahesh","Hyderabad",Arrays.asList(order,order1)); //Create object for JaxbContent JAXBContext context = JAXBContext.newInstance(Customer.class); //perform the marshalling Marshaller mar = context.createMarshaller(); //formatting purpose mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); mar.marshal(c, System.out); } } NOTE ==== 1) @XmlRootElement - It is particularly useful when you have a Java class that represents the entire XML document, and you want to specify it as the root element. 2) @XmlAccessorType - It is a Java annotation used in Java Architecture for XML Binding (JAXB) to specify how fields and properties of a Java class should be accessed and processed when performing XML marshaling and unmarshaling. * JAXB provides two main options for the XmlAccessType parameter of @XmlAccessorType: FIELD and PROPERTY. @XmlAccessorType(XmlAccessType.FIELD)- When you annotate a class with @XmlAccessorType(XmlAccessType.FIELD), JAXB will map fields directly to XML elements. This means that only fields marked with JAXB annotations will be considered for XML mapping, and property access methods (getters and setters) will be ignored. In this case, the name field will be mapped to an XML element directly, and the getter and setter methods for name will not be used for XML binding. @XmlAccessorType(XmlAccessType.PROPERTY)- JAXB will map the properties of the class (i.e., getter and setter methods) to XML elements. Fields can still be annotated with JAXB annotations to customize the XML mapping, but they are not required. In this case, the getName and setName methods are used for XML mapping, and the @XmlElement annotation on the getName method specifies that the name property should be mapped to an XML element. 3) @XmlElement - It is a Java annotation used in Java Architecture for XML Binding (JAXB) to customize the mapping of a field or property of a Java class to an XML element when marshaling (converting from Java objects to XML) and unmarshaling (converting from XML to Java objects) XML data. 4) @XmlElementWrapper - It is often used to wrap collections (e.g., lists, arrays, sets) of elements within a containing XML element. This can be useful when you want to represent a list of items as a child element within another XML element. This annotation allows you to specify the name, namespace, and other properties of the XML element that corresponds to the annotated field or property. Example ======= public class Book { private String title; private String author; private double price; // Constructors, getters, and setters @XmlElement(name = "bookTitle") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @XmlElement(namespace = "http://ashokit.com/books") public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @XmlElement public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } } pom.xml ======= 4.0.0 com.ashokit 43_Java_To_XML_Examples 0.0.1-SNAPSHOT 1.8 1.8 jakarta.xml.bind jakarta.xml.bind-api 4.0.0 com.sun.xml.bind jaxb-impl 4.0.1 runtime OUTPUT ====== Mahesh 123 Hyderabad 345 2500.0 645 3500.0 UnMarhshallingClient.java ========================= package com.ashokit; import java.io.File; import jakarta.xml.bind.JAXBContext; import jakarta.xml.bind.JAXBException; import jakarta.xml.bind.Unmarshaller; public class UnMarhshallingClient { public static void main(String[] args) throws JAXBException { //create JaxBContext object JAXBContext context = JAXBContext.newInstance(Customer.class); //Creating Unmarshaller Object Unmarshaller unmarshaller = context.createUnmarshaller(); Customer customer =(Customer)unmarshaller.unmarshal(new File("customer.xml")); //Displaying the customer information System.out.println("Customer::::" + customer); } } OUTPUT ====== Customer::::Customer [id=123, name=Mahesh, location=Hyderabad, order=[Order [orderId=345, billAmount=2500.0], Order [orderId=645, billAmount=3500.0]]] +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++