XML to Java: POJOs from a sample document
This XML to Java generator reads an XML document, converts it to an equivalent object tree, and writes one Java class per element structure, with private fields, getters and setters. Attributes and child elements are treated alike, so both end up as fields on the same class. Values are typed from their content: numbers become long or double, true/false become boolean, and everything else String.
Example
<library name="City Library">
<book isbn="0596007124" available="true">
<title>Head First Design Patterns</title>
<year>2004</year>
</book>
<book isbn="1449331815" available="false">
<title>Learning JavaScript</title>
<year>2012</year>
</book>
</library>
public class Library {
private List<Book> book;
private String name;
// getters and setters
}
public class Book {
private String title;
private long year;
private long isbn;
private boolean available;
// getters and setters
}
The root element <library> named the top-level class Library, its name attribute became a field, and the two <book> elements became List<Book>.
Watch the ISBN: numeric-looking text
XML has no data types; everything is text. The generator guesses types from the text, so 0596007124 was read as the number 596007124 and typed long, losing the leading zero. Identifiers like ISBNs, postal codes, phone numbers and account numbers should be String; change such fields by hand. Similarly, a version like 2.0 would become a double.
Binding the classes to XML with JAXB or Jackson
The generated classes describe the data, but Java XML libraries need to know which fields are attributes. With Jakarta XML Binding (JAXB):
@XmlRootElement(name = "library")
@XmlAccessorType(XmlAccessType.FIELD)
public class Library {
@XmlAttribute private String name;
@XmlElement(name = "book") private List<Book> book;
}
Use @XmlAttribute for attributes, @XmlElement for child elements and @XmlValue for the text of an element that also has attributes (the generator calls that field value). With Jackson's XmlMapper, the equivalents are @JacksonXmlProperty(isAttribute = true), @JacksonXmlText, and @JacksonXmlElementWrapper(useWrapping = false) for repeated elements that have no wrapper element. The optional helper code the generator adds (with Types only off) works on the JSON form of the data, not on XML.
Tips
- Include at least two of every repeating element in your sample; a single
<book>would be typed as oneBook, not a list. - Namespace prefixes are removed, so
<ns:book>maps to abookfield; add the namespace back in your JAXB annotations.
Format the result with the Java Formatter; for JSON input use JSON to Java, and check the XML first with the XML Validator. Generation runs in your browser.