0
# Input Source Management
1
2
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.
3
4
## Capabilities
5
6
### Input Builder
7
8
The main entry point for creating XML source instances from various input types.
9
10
```java { .api }
11
/**
12
* Universal builder method for supported input types
13
* @param object - Input object (String, File, URL, Document, etc.)
14
* @returns Builder instance for further configuration
15
*/
16
public static Builder from(Object object);
17
18
public class Input {
19
/** Create source from DOM Document */
20
public static Builder fromDocument(Document d);
21
22
/** Create source from any DOM Node */
23
public static Builder fromNode(Node n);
24
25
/** Create source from JAXB object */
26
public static JaxbBuilder fromJaxb(Object jaxbObject);
27
28
/** Create source from File object */
29
public static Builder fromFile(File f);
30
31
/** Create source from file name */
32
public static Builder fromFile(String name);
33
34
/** Create source from InputStream */
35
public static Builder fromStream(InputStream s);
36
37
/** Create source from Reader */
38
public static Builder fromReader(Reader r);
39
40
/** Create source from String content */
41
public static Builder fromString(String s);
42
43
/** Create source from byte array */
44
public static Builder fromByteArray(byte[] b);
45
46
/** Create source from NIO ReadableByteChannel */
47
public static Builder fromChannel(ReadableByteChannel c);
48
49
/** Create source from URL */
50
public static Builder fromURL(URL url);
51
52
/** Create source from URI object */
53
public static Builder fromURI(URI uri);
54
55
/** Create source from URI string */
56
public static Builder fromURI(String uri);
57
58
/** Create source from NIO Path */
59
public static Builder fromPath(Path path);
60
61
/** Create transformation builder from Source */
62
public static TransformationBuilder byTransforming(Source s);
63
64
/** Create transformation builder from Builder */
65
public static TransformationBuilder byTransforming(Builder b);
66
}
67
```
68
69
**Usage Examples:**
70
71
```java
72
import org.xmlunit.builder.Input;
73
import javax.xml.transform.Source;
74
75
// From String
76
Source xmlFromString = Input.fromString("<root><item>value</item></root>").build();
77
78
// From File
79
Source xmlFromFile = Input.fromFile("data.xml").build();
80
Source xmlFromFileObj = Input.fromFile(new File("data.xml")).build();
81
82
// From URL/URI
83
Source xmlFromUrl = Input.fromURL(new URL("http://example.com/data.xml")).build();
84
Source xmlFromUri = Input.fromURI("http://example.com/data.xml").build();
85
86
// From streams
87
FileInputStream fis = new FileInputStream("data.xml");
88
Source xmlFromStream = Input.fromStream(fis).build();
89
90
Reader reader = new FileReader("data.xml");
91
Source xmlFromReader = Input.fromReader(reader).build();
92
93
// From byte array
94
byte[] xmlBytes = "<root/>".getBytes("UTF-8");
95
Source xmlFromBytes = Input.fromByteArray(xmlBytes).build();
96
97
// From DOM Document
98
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
99
Document doc = db.parse(new File("data.xml"));
100
Source xmlFromDoc = Input.fromDocument(doc).build();
101
```
102
103
### Builder Interface
104
105
The builder pattern interface for configuring and creating Source instances.
106
107
```java { .api }
108
public interface Builder {
109
/** Build the final Source instance */
110
Source build();
111
}
112
113
// All Input.from* methods return Builder implementations
114
// that can be further configured before calling build()
115
```
116
117
### JAXB Integration
118
119
Specialized builder for creating XML sources from JAXB objects.
120
121
```java { .api }
122
public static abstract class JaxbBuilder implements Builder {
123
/** Configure custom Marshaller for JAXB serialization */
124
public JaxbBuilder withMarshaller(Object marshaller);
125
126
/** Use ObjectFactory for JAXB serialization */
127
public JaxbBuilder useObjectFactory();
128
129
/** Access to the configured JAXB object */
130
protected Object getObject();
131
132
/** Access to the custom marshaller */
133
protected Object getMarshaller();
134
135
/** Check if ObjectFactory should be used */
136
protected boolean getUseObjectFactory();
137
}
138
139
public interface JaxbBuilderFactory {
140
/** Create JaxbBuilder for given JAXB object */
141
JaxbBuilder createBuilder(Object object);
142
}
143
```
144
145
**Usage Examples:**
146
147
```java
148
import org.xmlunit.builder.Input;
149
import javax.xml.bind.JAXBContext;
150
import javax.xml.bind.Marshaller;
151
152
// JAXB object to XML
153
@XmlRootElement
154
public class Person {
155
@XmlElement
156
public String name;
157
@XmlElement
158
public int age;
159
}
160
161
Person person = new Person();
162
person.name = "John Doe";
163
person.age = 30;
164
165
// Simple JAXB conversion
166
Source jaxbSource = Input.fromJaxb(person).build();
167
168
// With custom marshaller
169
JAXBContext context = JAXBContext.newInstance(Person.class);
170
Marshaller marshaller = context.createMarshaller();
171
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
172
173
Source customJaxbSource = Input.fromJaxb(person)
174
.withMarshaller(marshaller)
175
.build();
176
177
// Using ObjectFactory
178
Source objectFactorySource = Input.fromJaxb(person)
179
.useObjectFactory()
180
.build();
181
```
182
183
### Input Transformation
184
185
Create sources by transforming existing sources with XSLT stylesheets.
186
187
```java { .api }
188
public interface TransformationBuilder extends TransformationBuilderBase<TransformationBuilder> {
189
/** Build the transformed source */
190
Source build();
191
}
192
193
public interface TransformationBuilderBase<T> {
194
/** Apply XSLT stylesheet to transformation */
195
T usingStylesheet(Source stylesheet);
196
197
/** Set XSLT parameter */
198
T withParameter(String name, Object value);
199
200
/** Set output property for transformation */
201
T withOutputProperty(String name, String value);
202
203
/** Configure TransformerFactory */
204
T withTransformerFactory(TransformerFactory factory);
205
206
/** Set URI resolver for transformation */
207
T withURIResolver(URIResolver resolver);
208
}
209
```
210
211
**Usage Examples:**
212
213
```java
214
import org.xmlunit.builder.Input;
215
import javax.xml.transform.Source;
216
217
// Transform XML with XSLT
218
Source originalXml = Input.fromString("<data><item>1</item><item>2</item></data>");
219
Source stylesheet = Input.fromFile("transform.xsl").build();
220
221
Source transformedXml = Input.byTransforming(originalXml)
222
.usingStylesheet(stylesheet)
223
.withParameter("title", "Transformed Data")
224
.withOutputProperty(OutputKeys.INDENT, "yes")
225
.build();
226
227
// Chain transformations
228
Source doubleTransformed = Input.byTransforming(
229
Input.byTransforming(originalXml)
230
.usingStylesheet(stylesheet)
231
)
232
.usingStylesheet(Input.fromFile("second-transform.xsl").build())
233
.build();
234
```
235
236
### Source Type Support
237
238
XMLUnit Input supports all standard javax.xml.transform.Source implementations and many common Java types.
239
240
**Supported Input Types:**
241
242
- **String**: XML content as string
243
- **File**: File system files
244
- **Path**: NIO2 Path objects
245
- **URL**: Remote or local URLs
246
- **URI**: URI objects and strings
247
- **InputStream**: Input streams
248
- **Reader**: Character readers
249
- **ReadableByteChannel**: NIO channels
250
- **byte[]**: Byte arrays
251
- **Document**: DOM Document objects
252
- **Node**: Any DOM Node
253
- **Source**: Existing JAXP Source objects
254
- **JAXB Objects**: Objects with JAXB annotations
255
256
**Source Output Types:**
257
258
All builders create instances of `javax.xml.transform.Source`, which can be:
259
- `DOMSource` for DOM-based inputs
260
- `StreamSource` for stream-based inputs
261
- `SAXSource` for SAX-based inputs
262
- `JAXBSource` for JAXB inputs
263
264
### Input Processing Options
265
266
Configure how input is processed and parsed.
267
268
```java { .api }
269
// Builder implementations may provide additional configuration methods
270
// depending on the input type and source format
271
272
// Example: DOM-based builders might support DocumentBuilderFactory configuration
273
// Example: Stream-based builders might support encoding specification
274
// Example: File-based builders might support URI resolution
275
```
276
277
**Common Processing Patterns:**
278
279
```java
280
// Handle different encodings
281
Source utf8Source = Input.fromFile("data-utf8.xml").build();
282
Source iso8859Source = Input.fromFile("data-iso8859.xml").build();
283
284
// Process from various stream sources
285
Source urlSource = Input.fromURL(new URL("https://api.example.com/data.xml")).build();
286
Source zipEntrySource = Input.fromStream(
287
new ZipInputStream(new FileInputStream("archive.zip"))
288
.getNextEntry()
289
).build();
290
291
// Handle classpath resources
292
InputStream resourceStream = getClass().getResourceAsStream("/test-data.xml");
293
Source resourceSource = Input.fromStream(resourceStream).build();
294
295
// Process generated content
296
StringBuilder xmlBuilder = new StringBuilder();
297
xmlBuilder.append("<?xml version='1.0'?>");
298
xmlBuilder.append("<generated>");
299
for (int i = 0; i < 10; i++) {
300
xmlBuilder.append("<item id='").append(i).append("'>Item ").append(i).append("</item>");
301
}
302
xmlBuilder.append("</generated>");
303
Source generatedSource = Input.fromString(xmlBuilder.toString()).build();
304
```
305
306
### Error Handling
307
308
Input creation can throw various exceptions based on the input type and processing requirements.
309
310
**Common Exceptions:**
311
312
- `IllegalArgumentException`: Invalid input parameters or unsupported types
313
- `IOException`: File system or network I/O errors
314
- `SAXException`: XML parsing errors
315
- `TransformerException`: XSLT transformation errors
316
- `JAXBException`: JAXB marshalling errors
317
318
**Exception Handling Examples:**
319
320
```java
321
try {
322
Source source = Input.fromFile("nonexistent.xml").build();
323
} catch (RuntimeException e) {
324
// Handle file not found or parsing errors
325
if (e.getCause() instanceof IOException) {
326
System.err.println("File not found: " + e.getMessage());
327
} else if (e.getCause() instanceof SAXException) {
328
System.err.println("XML parsing error: " + e.getMessage());
329
}
330
}
331
332
try {
333
Source jaxbSource = Input.fromJaxb(invalidObject).build();
334
} catch (RuntimeException e) {
335
if (e.getCause() instanceof JAXBException) {
336
System.err.println("JAXB marshalling failed: " + e.getMessage());
337
}
338
}
339
```
340
341
### Integration with Other XMLUnit Components
342
343
Input sources integrate seamlessly with other XMLUnit components.
344
345
```java
346
// Use with DiffBuilder
347
Diff diff = DiffBuilder.compare(Input.fromFile("expected.xml"))
348
.withTest(Input.fromString(actualXml))
349
.build();
350
351
// Use with Validator
352
Validator validator = Validator.forLanguage(Languages.W3C_XML_SCHEMA_NS_URI);
353
validator.setSchemaSources(Input.fromFile("schema.xsd").build());
354
ValidationResult result = validator.validateInstance(
355
Input.fromString(xmlToValidate).build()
356
);
357
358
// Use with XPath engine
359
JAXPXPathEngine xpath = new JAXPXPathEngine();
360
String value = xpath.evaluate("/root/item[1]",
361
Input.fromFile("data.xml").build()
362
);
363
364
// Use with Transform
365
Source transformed = Transform.source(Input.fromString(sourceXml).build())
366
.usingStylesheet(Input.fromFile("style.xsl").build())
367
.build();
368
```