In this code snippet, I will show how you can write to an XML file using JAXB and how to read from an XML file using JAXB. In this example I use two data structures I created showing two different ways how you customize the custom object to your liking.

Output of this example:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Character xmlns:ns2="com.crazyandcoding.jaxb.Character">
    <name>Colt</name>
    <Skill>
        <name>Strength</name>
        <level>34</level>
        <experience>4342</experience>
    </Skill>
    <Skill>
        <name>Magic</name>
        <level>12</level>
        <experience>1242</experience>
    </Skill>
</Character>
Colt
[Strength, Level: 34, Exp: 4342]
[Magic, Level: 12, Exp: 1242]
package com.crazyandcoding.jaxb;

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * The root of the XML file.
 * 
 * Example XML file. 
 * <Character> 
 * 		<name>Colt</name> 
 * 		<Skill> 
 * 			<name>Strength</name>
 *			<level>23</level> 
 *			<experience>3723</experience> 
 * 		</Skill> 
 * </Character>
 * 
 * Code snippet from www.crazyandcoding.com
 * @author Colt
 * 
 */
@XmlRootElement(name = "Character")
//specify the order in which the variables should be listed in the XML
@XmlType(propOrder = { "name", "skills" })
public class Character {

	private String name;

	private List<Skill> skills;

	public Character() {
	}

	public String getName() {
		return name;
	}

	@XmlElement(name = "name")
	public void setName(String name) {
		this.name = name;
	}

	public List<Skill> getSkills() {
		return skills;
	}

	@XmlElement(name = "Skill")
	public void setSkills(List<Skill> skills) {
		this.skills = skills;
	}

	@Override
	public String toString() {
		String s = name;
		for (int i = 0; i < skills.size(); i++) {
			s += "\n";
			s += "[" + skills.get(i).getName() + ", Level: "
					+ skills.get(i).getLevel() + ", Exp: "
					+ skills.get(i).getExperience() + "]";
		}
		return s;
	}
}
package com.crazyandcoding.jaxb;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 * A data structure containing information about a skill. In this class you can
 * see I don't specify any XML elements. But they will still be created.
 * 
 * Code snippet from www.crazyandcoding.com
 * @author Colt
 * 
 */
//specify the root element
@XmlRootElement(namespace = "com.crazyandcoding.jaxb.Character")
@XmlType(propOrder = { "name", "level", "experience" })
public class Skill {

	private String name;

	private int level;

	private int experience;

	public Skill() {

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getLevel() {
		return level;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public int getExperience() {
		return experience;
	}

	public void setExperience(int experience) {
		this.experience = experience;
	}

}
package com.crazyandcoding.jaxb;

import java.io.File;
import java.util.ArrayList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * Code snippet from www.crazyandcoding.com
 * 
 * @author Colt
 * 
 */
public class JAXBTester {

	public static void main(String[] args) {
		Character knight = new Character();
		knight.setName("Colt");

		Skill strength = new Skill();
		strength.setName("Strength");
		strength.setLevel(34);
		strength.setExperience(4342);

		Skill magic = new Skill();
		magic.setName("Magic");
		magic.setLevel(12);
		magic.setExperience(1242);

		knight.setSkills(new ArrayList<Skill>());
		knight.getSkills().add(strength);
		knight.getSkills().add(magic);

		try {
			// write the xml
			JAXBContext context = JAXBContext.newInstance(Character.class);
			Marshaller marshaller = context.createMarshaller();

			// makes the format pretty
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
					Boolean.TRUE);

			// prints to file
			marshaller.marshal(knight, new File(
					"D:\\Users\\Colt\\Desktop\\characters.xml"));

			// print to console
			marshaller.marshal(knight, System.out);


                        // read xml
			context = JAXBContext.newInstance(Character.class);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			Character newKnight = (Character) unmarshaller.unmarshal(new File(
					"D:\\Users\\Colt\\Desktop\\characters.xml"));

			System.out.println(newKnight.toString());
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>