XMLUnit Core is a comprehensive XML testing library for Java that provides powerful tools for comparing XML documents, validating XML against schemas, and evaluating XPath expressions.
Flexible input source creation and transformation for XML documents from various formats including files, strings, streams, DOM documents, and JAXB objects. XMLUnit's Input class provides a comprehensive fluent API for creating javax.xml.transform.Source instances.
The main entry point for creating XML source instances from various input types.
/**
* Universal builder method for supported input types
* @param object - Input object (String, File, URL, Document, etc.)
* @returns Builder instance for further configuration
*/
public static Builder from(Object object);
public class Input {
/** Create source from DOM Document */
public static Builder fromDocument(Document d);
/** Create source from any DOM Node */
public static Builder fromNode(Node n);
/** Create source from JAXB object */
public static JaxbBuilder fromJaxb(Object jaxbObject);
/** Create source from File object */
public static Builder fromFile(File f);
/** Create source from file name */
public static Builder fromFile(String name);
/** Create source from InputStream */
public static Builder fromStream(InputStream s);
/** Create source from Reader */
public static Builder fromReader(Reader r);
/** Create source from String content */
public static Builder fromString(String s);
/** Create source from byte array */
public static Builder fromByteArray(byte[] b);
/** Create source from NIO ReadableByteChannel */
public static Builder fromChannel(ReadableByteChannel c);
/** Create source from URL */
public static Builder fromURL(URL url);
/** Create source from URI object */
public static Builder fromURI(URI uri);
/** Create source from URI string */
public static Builder fromURI(String uri);
/** Create source from NIO Path */
public static Builder fromPath(Path path);
/** Create transformation builder from Source */
public static TransformationBuilder byTransforming(Source s);
/** Create transformation builder from Builder */
public static TransformationBuilder byTransforming(Builder b);
}Usage Examples:
import org.xmlunit.builder.Input;
import javax.xml.transform.Source;
// From String
Source xmlFromString = Input.fromString("<root><item>value</item></root>").build();
// From File
Source xmlFromFile = Input.fromFile("data.xml").build();
Source xmlFromFileObj = Input.fromFile(new File("data.xml")).build();
// From URL/URI
Source xmlFromUrl = Input.fromURL(new URL("http://example.com/data.xml")).build();
Source xmlFromUri = Input.fromURI("http://example.com/data.xml").build();
// From streams
FileInputStream fis = new FileInputStream("data.xml");
Source xmlFromStream = Input.fromStream(fis).build();
Reader reader = new FileReader("data.xml");
Source xmlFromReader = Input.fromReader(reader).build();
// From byte array
byte[] xmlBytes = "<root/>".getBytes("UTF-8");
Source xmlFromBytes = Input.fromByteArray(xmlBytes).build();
// From DOM Document
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = db.parse(new File("data.xml"));
Source xmlFromDoc = Input.fromDocument(doc).build();The builder pattern interface for configuring and creating Source instances.
public interface Builder {
/** Build the final Source instance */
Source build();
}
// All Input.from* methods return Builder implementations
// that can be further configured before calling build()Specialized builder for creating XML sources from JAXB objects.
public static abstract class JaxbBuilder implements Builder {
/** Configure custom Marshaller for JAXB serialization */
public JaxbBuilder withMarshaller(Object marshaller);
/** Use ObjectFactory for JAXB serialization */
public JaxbBuilder useObjectFactory();
/** Access to the configured JAXB object */
protected Object getObject();
/** Access to the custom marshaller */
protected Object getMarshaller();
/** Check if ObjectFactory should be used */
protected boolean getUseObjectFactory();
}
public interface JaxbBuilderFactory {
/** Create JaxbBuilder for given JAXB object */
JaxbBuilder createBuilder(Object object);
}Usage Examples:
import org.xmlunit.builder.Input;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
// JAXB object to XML
@XmlRootElement
public class Person {
@XmlElement
public String name;
@XmlElement
public int age;
}
Person person = new Person();
person.name = "John Doe";
person.age = 30;
// Simple JAXB conversion
Source jaxbSource = Input.fromJaxb(person).build();
// With custom marshaller
JAXBContext context = JAXBContext.newInstance(Person.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Source customJaxbSource = Input.fromJaxb(person)
.withMarshaller(marshaller)
.build();
// Using ObjectFactory
Source objectFactorySource = Input.fromJaxb(person)
.useObjectFactory()
.build();Create sources by transforming existing sources with XSLT stylesheets.
public interface TransformationBuilder extends TransformationBuilderBase<TransformationBuilder> {
/** Build the transformed source */
Source build();
}
public interface TransformationBuilderBase<T> {
/** Apply XSLT stylesheet to transformation */
T usingStylesheet(Source stylesheet);
/** Set XSLT parameter */
T withParameter(String name, Object value);
/** Set output property for transformation */
T withOutputProperty(String name, String value);
/** Configure TransformerFactory */
T withTransformerFactory(TransformerFactory factory);
/** Set URI resolver for transformation */
T withURIResolver(URIResolver resolver);
}Usage Examples:
import org.xmlunit.builder.Input;
import javax.xml.transform.Source;
// Transform XML with XSLT
Source originalXml = Input.fromString("<data><item>1</item><item>2</item></data>");
Source stylesheet = Input.fromFile("transform.xsl").build();
Source transformedXml = Input.byTransforming(originalXml)
.usingStylesheet(stylesheet)
.withParameter("title", "Transformed Data")
.withOutputProperty(OutputKeys.INDENT, "yes")
.build();
// Chain transformations
Source doubleTransformed = Input.byTransforming(
Input.byTransforming(originalXml)
.usingStylesheet(stylesheet)
)
.usingStylesheet(Input.fromFile("second-transform.xsl").build())
.build();XMLUnit Input supports all standard javax.xml.transform.Source implementations and many common Java types.
Supported Input Types:
Source Output Types:
All builders create instances of javax.xml.transform.Source, which can be:
DOMSource for DOM-based inputsStreamSource for stream-based inputsSAXSource for SAX-based inputsJAXBSource for JAXB inputsConfigure how input is processed and parsed.
// Builder implementations may provide additional configuration methods
// depending on the input type and source format
// Example: DOM-based builders might support DocumentBuilderFactory configuration
// Example: Stream-based builders might support encoding specification
// Example: File-based builders might support URI resolutionCommon Processing Patterns:
// Handle different encodings
Source utf8Source = Input.fromFile("data-utf8.xml").build();
Source iso8859Source = Input.fromFile("data-iso8859.xml").build();
// Process from various stream sources
Source urlSource = Input.fromURL(new URL("https://api.example.com/data.xml")).build();
Source zipEntrySource = Input.fromStream(
new ZipInputStream(new FileInputStream("archive.zip"))
.getNextEntry()
).build();
// Handle classpath resources
InputStream resourceStream = getClass().getResourceAsStream("/test-data.xml");
Source resourceSource = Input.fromStream(resourceStream).build();
// Process generated content
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.append("<?xml version='1.0'?>");
xmlBuilder.append("<generated>");
for (int i = 0; i < 10; i++) {
xmlBuilder.append("<item id='").append(i).append("'>Item ").append(i).append("</item>");
}
xmlBuilder.append("</generated>");
Source generatedSource = Input.fromString(xmlBuilder.toString()).build();Input creation can throw various exceptions based on the input type and processing requirements.
Common Exceptions:
IllegalArgumentException: Invalid input parameters or unsupported typesIOException: File system or network I/O errorsSAXException: XML parsing errorsTransformerException: XSLT transformation errorsJAXBException: JAXB marshalling errorsException Handling Examples:
try {
Source source = Input.fromFile("nonexistent.xml").build();
} catch (RuntimeException e) {
// Handle file not found or parsing errors
if (e.getCause() instanceof IOException) {
System.err.println("File not found: " + e.getMessage());
} else if (e.getCause() instanceof SAXException) {
System.err.println("XML parsing error: " + e.getMessage());
}
}
try {
Source jaxbSource = Input.fromJaxb(invalidObject).build();
} catch (RuntimeException e) {
if (e.getCause() instanceof JAXBException) {
System.err.println("JAXB marshalling failed: " + e.getMessage());
}
}Input sources integrate seamlessly with other XMLUnit components.
// Use with DiffBuilder
Diff diff = DiffBuilder.compare(Input.fromFile("expected.xml"))
.withTest(Input.fromString(actualXml))
.build();
// Use with Validator
Validator validator = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
validator.setSchemaSources(Input.fromFile("schema.xsd").build());
ValidationResult result = validator.validateInstance(
Input.fromString(xmlToValidate).build()
);
// Use with XPath engine
JAXPXPathEngine xpath = new JAXPXPathEngine();
String value = xpath.evaluate("/root/item[1]",
Input.fromFile("data.xml").build()
);
// Use with Transform
Source transformed = Transform.source(Input.fromString(sourceXml).build())
.usingStylesheet(Input.fromFile("style.xsl").build())
.build();Install with Tessl CLI
npx tessl i tessl/maven-org-xmlunit--xmlunit-core