Java jaxb string to xml

Java Guides

Java Architecture for XML Binding (JAXB) is a Java standard that allows Java developers to map Java classes to XML representations. JAXB enables to marshal Java objects into XML and unmarshal XML back into Java objects.

Marshalling is the process of transforming Java objects into XML documents.
Unmarshalling is the process of reading XML documents into Java objects.

In Java 9, JAXB has moved into a separate module java.xml. In Java 9 and Java 10 we need to use the —add-modules=java.xml.bind option. In Java 11, JAXB has been removed from JDK and we need to add it to the project as a separate library via Maven or Gradle.

Video Tutorial

Development Steps

1. Create a Simple Maven Project

2. Add Maven Dependencies

project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> modelVersion>4.0.0modelVersion> groupId>net.javaguides.xmlgroupId> artifactId>java-xml-tutorialartifactId> version>0.0.1-SNAPSHOTversion> dependencies> dependency> groupId>javax.xml.bindgroupId> artifactId>jaxb-apiartifactId> version>2.2.11version> dependency> dependency> groupId>com.sun.xml.bindgroupId> artifactId>jaxb-coreartifactId> version>2.2.11version> dependency> dependency> groupId>com.sun.xml.bindgroupId> artifactId>jaxb-implartifactId> version>2.2.11version> dependency> dependency> groupId>javax.activationgroupId> artifactId>activationartifactId> version>1.1.1version> dependency> dependencies> build> sourceDirectory>src/main/javasourceDirectory> plugins> plugin> artifactId>maven-compiler-pluginartifactId> version>3.5.1version> configuration> source>1.8source> target>1.8target> configuration> plugin> plugins> build> project>

3. Create POJO classes and Add JAXB annotations

  1. @XmlRootElement : This is a must-have an annotation for the Object to be used in JAXB. It defines the root element for the XML content.
  2. @XmlType : It maps the class to the XML schema type. We can use it for ordering the elements in the XML.
  3. @XmlTransient : This will make sure that the Object property is not written to the XML.
  4. @XmlAttribute : This will create the Object property as an attribute.
  5. @XmlElement(name = “ABC”) : This will create the element with name “ABC”

3.1 Book POJO Class

package net.javaguides.javaxmlparser.jaxb; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "book") @XmlType(propOrder = < "author", "name", "publisher", "isbn" >) public class Book < private String name; private String author; private String publisher; private String isbn; @XmlElement(name = "title") public String getName() < return name; > public void setName(String name) < this.name = name; > public String getAuthor() < return author; > public void setAuthor(String author) < this.author = author; > public String getPublisher() < return publisher; > public void setPublisher(String publisher) < this.publisher = publisher; > public String getIsbn() < return isbn; > public void setIsbn(String isbn) < this.isbn = isbn; > >

3.2 Bookstore POJO Class

package net.javaguides.javaxmlparser.jaxb; import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(namespace = "net.javaguides.javaxmlparser.jaxb") public class Bookstore < @XmlElementWrapper(name = "bookList") @XmlElement(name = "book") private List  Book > bookList; private String name; private String location; public void setBookList(List < Book > bookList) < this.bookList = bookList; > public List < Book > getBooksList() < return bookList; > 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; > >

4. Convert Java Object to an XML

package net.javaguides.javaxmlparser.jaxb; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; /** * Marshaller Class - Convert Java Object to XML * * @author Ramesh Fadatare * */ public class BookMain < private static final String BOOKSTORE_XML = "bookstore-jaxb.xml"; public static void main(String[] args) throws JAXBException, IOException < List  Book > bookList = new ArrayList < Book > (); // create books Book book1 = new Book(); book1.setIsbn("978-0134685991"); book1.setName("Effective Java"); book1.setAuthor("Joshua Bloch"); book1.setPublisher("Amazon"); bookList.add(book1); Book book2 = new Book(); book2.setIsbn("978-0596009205"); book2.setName("Head First Java, 2nd Edition"); book2.setAuthor("Kathy Sierra"); book2.setPublisher("amazon"); bookList.add(book2); // create bookstore, assigning book Bookstore bookstore = new Bookstore(); bookstore.setName("Amazon Bookstore"); bookstore.setLocation("Newyorkt"); bookstore.setBookList(bookList); convertObjectToXML(bookstore); > private static void convertObjectToXML(Bookstore bookstore) throws JAXBException, FileNotFoundException < // create JAXB context and instantiate marshaller JAXBContext context = JAXBContext.newInstance(Bookstore.class); Marshaller m = context.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); // Write to System.out m.marshal(bookstore, System.out); // Write to File m.marshal(bookstore, new File(BOOKSTORE_XML)); > >

The above program creates a file named bookstore-jaxb.xml and stored Book objects into this XML file:

xml version="1.0" encoding="UTF-8" standalone="yes"?> ns2:bookstore xmlns:ns2="net.javaguides.javaxmlparser.jaxb"> bookList> book> author>Joshua Blochauthor> title>Effective Javatitle> publisher>Amazonpublisher> isbn>978-0134685991isbn> book> book> author>Kathy Sierraauthor> title>Head First Java, 2nd Editiontitle> publisher>amazonpublisher> isbn>978-0596009205isbn> book> bookList> location>Newyorktlocation> name>Amazon Bookstorename> ns2:bookstore>

5. Convert XML to Java Object

Let’s convert the XML document that was generated in the above example to Java object.

Let’s convert a bookstore-jaxb.xml document into Java Object:

package net.javaguides.javaxmlparser.jaxb; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; /** * Unmarshaller Class - Convert XML to Object in Java * @author Ramesh Fadatare * */ public class BookMain < private static final String BOOKSTORE_XML = "bookstore-jaxb.xml"; public static void main(String[] args) throws JAXBException, IOException < convertXMLToObject(); >private static Bookstore convertXMLToObject() < try < JAXBContext context = JAXBContext.newInstance(Bookstore.class); Unmarshaller un = context.createUnmarshaller(); Bookstore bookstore = (Bookstore) un.unmarshal(new File(BOOKSTORE_XML)); List  Book > list = bookstore.getBooksList(); for (Book book: list) < System.out.println("Book: " + book.getName() + " from " + book.getAuthor()); > > catch (JAXBException e) < e.printStackTrace(); > return null; > >
Book: Effective Java from Joshua Bloch Book: Head First Java, 2nd Edition from Kathy Sierra

Conclusion

In this tutorial, we have seen how to use JAXB API to convert Java object to/from XML. In this tutorial, we have used Java 11 to develop and run the examples.

Источник

JAXB Tutorial: How to Marshal and Unmarshal XML

This JAXB tutorial describes how to use JAXB to marshal and unmarshal XML strings using either Spring or the standard javax.xml.bind interfaces.

The samples below are using XML strings instead of files, but could easily be adapted to files if needed.

Spring’s Jaxb2Marshaller

Configuration

To use Spring’s Jaxb2Marshaller , you will need the spring-oxm dependency, which you may already have, since it is used by other major spring components.

 org.springframework spring-oxm 4.2.4.RELEASE 

To configure the Jaxb2Marshaller in your Spring context, add the config XML below. Be sure to add all root packages that contain the JAXB classes.

    com.intertech.consulting org.w3._2000._09.xmldsig_ org.w3._2003._05.soap_envelope org.xmlsoap.schemas.ws   

Unmarshalling

To unmarshal an XML string into a JAXB object, just inject the Jaxb2Marshaller and call the unmarshal() method.

public class DoSomethingService < @Autowired private Jaxb2Marshaller marshaller; public JAXBElementunmarshal(String xmlString) < return (JAXBElement) marshaller.unmarshal(new StringSource(xmlString)); > >

Marshalling

To marshal a JAXB object into an XML string, you will need to create a StringResult and pass that to the marshal() method.

public class DoSomethingService < @Autowired private Jaxb2Marshaller marshaller; public String marshal(JAXBElementjaxbElement) < try < StringResult result = new StringResult(); marshaller.marshal(jaxbElement, result); return result.toString(); >catch (Exception e) < throw new IllegalStateException(e); >> >

Java’s XML Packages

Java 6 and later have the standard JAXB interfaces and factories for processing xml available in the java.xml.bind package. You can find more info about JAXB on the JAXB project web site.

UNMARSHALLING

To unmarshal an xml string into a JAXB object, you will need to create an Unmarshaller from the JAXBContext , then call the unmarshal() method with a source/reader and the expected root object.

import javax.xml.bind.*; import javax.xml.stream.*; import java.io.*; public class DoSomethingService < // JAXBContext is thread safe and can be created once private JAXBContext jaxbContext; public DoSomethingService() < try < // create context with ":" separated list of packages that // contain your JAXB ObjectFactory classes jaxbContext = JAXBContext.newInstance( "com.intertech.consulting" + ":org.w3._2003._05.soap_envelope"); >catch (Exception e) < throw new IllegalStateException(e); >> public JAXBElement unmarshal(String xmlString) < try < // Unmarshallers are not thread-safe. Create a new one every time. Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StringReader(xmlString)); return unmarshaller.unmarshal(reader, YourRootObject.class); >catch (Exception e) < throw new IllegalStateException(e); >> >

Marshalling

To marshal a JAXB object into an XML string, you will need to create a a Marshaller from the JAXBContext and pass a Writer target to the marshal() method.

import javax.xml.bind.*; import javax.xml.stream.*; import java.io.*; public class DoSomethingService < // JAXBContext is thread safe and can be created once private JAXBContext jaxbContext; public DoSomethingService() < try < // create context with ":" separated list of packages that // contain your JAXB ObjectFactory classes jaxbContext = JAXBContext.newInstance( "com.intertech.consulting" + ":org.w3._2003._05.soap_envelope"); >catch (Exception e) < throw new IllegalStateException(e); >> public String marshal(JAXBElement jaxbElement) < try < // Marshallers are not thread-safe. Create a new one every time. Marshaller marshaller = jaxbContext.createMarshaller(); StringWriter stringWriter = new StringWriter(); marshaller.marshal(jaxbElement, stringWriter); return stringWriter.toString(); >catch (Exception e) < throw new IllegalStateException(e); >> >

As you can see, the Spring mechanisms are pretty clean, but if you are not using Spring, the Java mechanisms are easy to work with as well.

Next up in this JAXB tutorial series we’ll see how to configure the namespace prefixes.

JAXB Tutorial Side Note

If you’ve ever wondered about the correct spelling of marshalling (vs marshaling), there’s a brief summary on Stack Overflow… (2 l’s is acceptable)

Источник

JAXB Write Java Object to XML Example

Java example to write Java object to XML. Information stored in Java objects fields can written into XML file or simply XML string as well.

1) Convert Java Object to XML String

To write Java object to XML String , first get the JAXBContext . It is entry point to the JAXB API and provides methods to unmarshal, marshal and validate operations.

Now get the Marshaller instance from JAXBContext . It’s marshal() method marshals Java object into XML. Now this XML can be written to different outputs e.g. string, file or stream.

package com.howtodoinjava.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample < public static void main(String[] args) < //Java object. We will convert it to XML. Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); >private static void jaxbObjectToXML(Employee employee) < try < //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Print XML String to Console StringWriter sw = new StringWriter(); //Write XML to StringWriter jaxbMarshaller.marshal(employee, sw); //Verify XML Content String xmlContent = sw.toString(); System.out.println( xmlContent ); >catch (JAXBException e) < e.printStackTrace(); >> >

2) Convert Java Object to XML File

Writing XML to file is very similar to above example. You only need to provide XML file location where you want to write the file.

package com.howtodoinjava.demo; import java.io.File; import java.io.StringWriter; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; public class JaxbExample < public static void main(String[] args) < //Java object. We will convert it to XML. Employee employee = new Employee(1, "Lokesh", "Gupta", new Department(101, "IT")); //Method which uses JAXB to convert object to XML jaxbObjectToXML(employee); >private static void jaxbObjectToXML(Employee employee) < try < //Create JAXB Context JAXBContext jaxbContext = JAXBContext.newInstance(Employee.class); //Create Marshaller Marshaller jaxbMarshaller = jaxbContext.createMarshaller(); //Required formatting?? jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); //Store XML to File File file = new File("employee.xml"); //Writes XML file to file-system jaxbMarshaller.marshal(employee, file); >catch (JAXBException e) < e.printStackTrace(); >> >

If you want to read the XML from file to Java object again, then use this method.

String fileName = "employee.xml"; //Call method which read the XML file above jaxbXmlFileToObject(fileName); private static void jaxbXmlFileToObject(String fileName) < File xmlFile = new File(fileName); JAXBContext jaxbContext; try < jaxbContext = JAXBContext.newInstance(Employee.class); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); Employee employee = (Employee) jaxbUnmarshaller.unmarshal(xmlFile); System.out.println(employee); >catch (JAXBException e) < e.printStackTrace(); >>
Employee [id=1, firstName=Lokesh, lastName=Gupta, department=Department [id=101, name=IT]]

Drop me your questions in comments section.

Источник

Читайте также:  Jpg to png in cpp
Оцените статью