My linux world » Java – xml

Java - xml



If you use maven, add this to your pom.xml :



Let’s deal with the following model for our examples : :

@XmlType(propOrder={"fistname", "name"})
public class User {
	private String name = null;
	private String fistname = null;
	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getFistname() {
		return fistname;
	public void setFistname(String fistname) {
		this.fistname = fistname;
} :

public class Users {
	private List<User> users = new ArrayList<User>();
	public List<User> getUsers() {
		return users;
	public void setUsers(List<User> users) {
		this.users = users;

Convert Object to XML

Let’s create a user :

// User john doe :
User user = new User();
// Add the user to the user list (users)
Users users = new Users();

Now convert it to xml :

File outputXml = "/tmp/users.xml";
JAXBContext jaxbContext = JAXBContext.newInstance(Users.class);
Marshaller marshaller = jaxbContext.createMarshaller();
// output pretty printed
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// marshal object to xml
marshaller.marshal(users, outputXml );

The file “/tmp/users.xml” will look like this :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>


Convert Object to XSD

Convert Users to xsd :

File outputXsd = "/tmp/users.xsd";
SchemaOutputResolver schemaOutputResolver = new SchemaOutputResolver () {			
  public Result createOutput(String arg0, String arg1) throws IOException {
    return new StreamResult(outputXsd );
JAXBContext jaxbContext = JAXBContext.newInstance(Users.class);

The file “/tmp/users.xsd” will look like this :

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<xs:schema version="1.0" xmlns:xs="">
  <xs:element name="user" type="user"/>
  <xs:element name="users" type="users"/>
  <xs:complexType name="users">
      <xs:element ref="user" minOccurs="0" maxOccurs="unbounded"/>
  <xs:complexType name="user">
      <xs:element name="fistname" type="xs:string" minOccurs="0"/>
      <xs:element name="name" type="xs:string" minOccurs="0"/>

Convert XML to Object

File xmlFile = "/tmp/users.xml";
JAXBContext jaxbContext = JAXBContext.newInstance(Users.class);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
Users users = (Users) unmarshaller.unmarshal(xmlFile );

Copyright © 2023 My linux world - by Marc RABAHI
Design by Marc RABAHI and encelades.

Fork me on GitHub