Skip to main content

XML Parsers

The XmlParser class is used to parse XML into POJOs.

When to use it​

Use XmlParser to read XML produced by XmlSerializer, or XML in the same element conventions, back into beans, collections and maps. For XML with a different shape, such as an arbitrary third-party schema, map the elements with the @Xml annotation or parse into a generic JsonMap. The parser reads through a StAX reader; the secure-XML library (commons-secure-xml) must be on the classpath.

Example​

import java.util.*;
import org.apache.juneau.marshall.xml.*;

public class XmlParserExample {

public static class Person {
public String name;
public int age;
}

public static void main(String[] args) throws Exception {
String xml = "<object><name>John Smith</name><age>45</age></object>";

// Parse into a bean with the default parser.
Person person = XmlParser.DEFAULT.read(xml, Person.class);

// Parse a list; the second class is the element type.
List<Integer> numbers = XmlParser.DEFAULT.read(
"<array><number>1</number><number>2</number></array>", List.class, Integer.class);

System.out.println(person.name + " " + person.age + " " + numbers);
}
}

Parsers are immutable and thread-safe, so build one once and reuse it.

Options​

The following pre-configured parsers are provided for convenience:

InstanceAccepts
XmlParser.DEFAULTXML with the default settings.

For anything else, start from the builder's create() method. The settings readers reach for first:

Builder methodEffect
preserveRootElement()Keep the root element name when parsing into a map, so it can be serialized back unchanged.
validating()Validate the XML against its DTD while parsing.
reporter(...)Set the XMLReporter that receives parse warnings.
resolver(...)Set the XMLResolver used to resolve external entities.
eventAllocator(...)Set the StAX XMLEventAllocator used to create events.
trimStrings()Trim whitespace from parsed string values.
beanDictionary(Class...)Classes the parser may instantiate from type-name attributes.
swaps(Class...)Object swaps that convert parsed values into other types.

The class hierarchy for the builder of this parser is below. Refer to the builder javadocs for the full set of configurable settings.

Context.BuilderMarshallingContextable.BuilderParser.BuilderReaderParser.BuilderXmlParser.Builder

See also​