DEV Community 👩‍💻👨‍💻

Cover image for How to unmarshall xml string to java object with JAXB
Adrian Matei for Codever

Posted on • Updated on • Originally published at

How to unmarshall xml string to java object with JAXB

Given the following Superhero class:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

import lombok.Getter;
import lombok.Setter;

@XmlRootElement(name = "super-hero")
class SuperHero {
  @XmlElement(name = "name")
  String name;

  @XmlElement(name = "super-power")
  String superPower;
Enter fullscreen mode Exit fullscreen mode

You can convert an XML String to a SuperHero instance with the following code:

import static org.junit.jupiter.api.Assertions.assertEquals;


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

import org.junit.jupiter.api.Test;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;

class TestXmlStringToObjectUnmarshalling {

  static final String superHeroXml =
      "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"
          + "<super-hero>"
          + "  <name>Superman</name>"
          + "  <super-power>Flight</super-power>"
          + "</super-hero>";

  void testXmlUnmarshalling() throws JAXBException {
    JAXBContext jaxbContext = JAXBContext.newInstance(SuperHero.class);
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    StringReader reader = new StringReader(superHeroXml);
    SuperHero superHero = (SuperHero) unmarshaller.unmarshal(reader);

    assertEquals("Flight", superHero.getSuperPower());

Enter fullscreen mode Exit fullscreen mode


  • create a JAXBContext which includes the SuperHero class - JAXBContext.newInstance(SuperHero.class)
  • create a JAXB Unmarshaller and apply the unmarshal method to a StringReader wrapping the text (it could be also a FileReader or any other Reader for that matter)

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Top comments (0)

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆