Convert XML to CSV in Java by parsing the document into DOM records, selecting one repeated element name, flattening each record into a row, and writing RFC-style CSV.
XML has no universal record-to-table mapping, so the conversion must define its record boundary and field rules before code is written. The example below targets a predictable feed containing repeated records with attributes and scalar child elements. It uses only standard Java classes and deliberately does not try to interpret arbitrary XML.

Choose the record boundary before writing Java
Start by identifying the exact qualified name shared by the records that should become rows. For example, a catalog might contain repeated item elements, while a namespaced feed might use ns:item. The name is case-sensitive. In the Java example, each result from getElementsByTagName becomes one record and one output row.
| XML feature | CSV treatment | Important limitation |
|---|---|---|
| Record attribute | One column prefixed with @, such as @id | The prefix distinguishes an attribute from a child element with the same name. |
| Direct scalar child | One column containing its trimmed text | Nested markup is represented only by descendant text. |
| Repeated direct child | One cell containing a compact JSON array | The destination importer must understand the JSON array format. |
| Missing field in a record | An empty CSV field | The output remains rectangular, but empty values need validation. |
| Direct non-whitespace text | A #text column | Mixed-content ordering is not preserved. |
Columns follow a deterministic union. Fields found in the first record appear first, while fields encountered only in later records are appended. This makes the header stable for the input, although it does not imply that the XML has a declared table schema.
Convert the XML with a standard Java DOM parser
The following Java 11+ example reads an XML file, selects the requested record name, constructs the column union, writes UTF-8 CSV without a byte-order mark, and uses CRLF between records. Its parser configuration rejects DOCTYPE declarations and disables external entity loading.
- Save the implementation below as XmlToCsv.java.
- Compile it with javac XmlToCsv.java.
- Run java XmlToCsv input.xml output.csv item true, replacing the record name with the exact qualified name used by your feed.
- Check the printed record and column counts against the source before using the CSV in a production workflow.
Complete Java implementation
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.util.*;
import org.w3c.dom.*;
public class XmlToCsv {
public static void main(String[] args) throws Exception {
if (args.length < 3 || args.length > 4) {
throw new IllegalArgumentException(
"Usage: java XmlToCsv input.xml output.csv record-name [protect]");
}
boolean protect = args.length == 3 || Boolean.parseBoolean(args[3]);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
Document doc = factory.newDocumentBuilder().parse(Path.of(args[0]).toFile());
NodeList matches = doc.getElementsByTagName(args[2]);
if (matches.getLength() == 0) {
throw new IllegalArgumentException("No records matched " + args[2]);
}
List<Element> records = new ArrayList<>();
Set<String> columns = new LinkedHashSet<>();
for (int i = 0; i < matches.getLength(); i++) {
Element record = (Element) matches.item(i);
records.add(record);
NamedNodeMap attributes = record.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attribute = attributes.item(j);
if (!isNamespaceDeclaration(attribute)) {
columns.add("@" + attribute.getNodeName());
}
}
NodeList children = record.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeType() == Node.ELEMENT_NODE) {
columns.add(child.getNodeName());
} else if (isText(child) && !child.getNodeValue().trim().isEmpty()) {
columns.add("#text");
}
}
}
System.out.println("Records: " + records.size() + ", columns: " + columns.size());
try (BufferedWriter out = Files.newBufferedWriter(
Path.of(args[1]), StandardCharsets.UTF_8)) {
writeRow(out, columns, false);
for (Element record : records) {
Map<String, List<String>> values = new LinkedHashMap<>();
NamedNodeMap attributes = record.getAttributes();
for (int j = 0; j < attributes.getLength(); j++) {
Node attribute = attributes.item(j);
if (!isNamespaceDeclaration(attribute)) {
values.computeIfAbsent("@" + attribute.getNodeName(),
key -> new ArrayList<>()).add(attribute.getNodeValue());
}
}
StringBuilder directText = new StringBuilder();
NodeList children = record.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
if (child.getNodeType() == Node.ELEMENT_NODE) {
values.computeIfAbsent(child.getNodeName(), key -> new ArrayList<>())
.add(child.getTextContent().trim());
} else if (isText(child)) {
directText.append(child.getNodeValue());
}
}
if (!directText.toString().trim().isEmpty()) {
values.computeIfAbsent("#text", key -> new ArrayList<>())
.add(directText.toString().trim());
}
List<String> row = new ArrayList<>();
for (String column : columns) {
List<String> found = values.get(column);
if (found == null || found.isEmpty()) {
row.add("");
} else if (found.size() == 1) {
row.add(found.get(0));
} else {
row.add(jsonArray(found));
}
}
writeRow(out, row, protect);
}
}
}
static boolean isText(Node node) {
return node.getNodeType() == Node.TEXT_NODE
|| node.getNodeType() == Node.CDATA_SECTION_NODE;
}
static boolean isNamespaceDeclaration(Node attribute) {
return "http://www.w3.org/2000/xmlns/".equals(attribute.getNamespaceURI());
}
static String jsonArray(List<String> values) {
StringBuilder json = new StringBuilder("[");
for (int i = 0; i < values.size(); i++) {
if (i > 0) json.append(',');
json.append('"').append(escapeJson(values.get(i))).append('"');
}
return json.append(']').toString();
}
static String escapeJson(String value) {
return value.replace("\\", "\\\\").replace("\"", "\\\"")
.replace("\r", "\\r").replace("\n", "\\n").replace("\t", "\\t");
}
static void writeRow(BufferedWriter out, Iterable<String> fields,
boolean protect) throws IOException {
int index = 0;
for (String field : fields) {
if (index++ > 0) out.write(',');
writeField(out, field, protect);
}
out.write("\r\n");
}
static void writeField(BufferedWriter out, String value, boolean protect)
throws IOException {
String cell = value;
if (protect && !cell.isEmpty()
&& "=+-@".indexOf(cell.charAt(0)) >= 0) {
cell = "\t" + cell;
}
boolean quote = cell.indexOf(',') >= 0 || cell.indexOf('"') >= 0
|| cell.indexOf('\t') >= 0 || cell.indexOf('\r') >= 0
|| cell.indexOf('\n') >= 0;
if (quote) {
out.write('"');
out.write(cell.replace("\"", "\"\""));
out.write('"');
} else {
out.write(cell);
}
}
}
The fourth argument controls formula protection for data cells. Omit it to enable protection, or pass false when a programmatic importer requires the exact original text. For a namespaced record, use a command such as java XmlToCsv catalog.xml catalog.csv ns:item true. The example matches that qualified name literally and does not normalize one namespace prefix into another.
Serialize CSV values without corrupting cells
Joining values with commas is not safe CSV serialization. A field containing a comma, double quote, tab, carriage return, or line feed must be enclosed in double quotes, and embedded double quotes must be doubled. The example also writes CRLF record endings, matching the commonly used RFC 4180 CSV format.
The CSV writer does not trim spaces; the XML mapping trims direct-child text before passing it to the writer. Missing fields remain empty, while values that contain line breaks stay inside one quoted CSV field rather than becoming extra records.
Spreadsheet applications can interpret a cell beginning with =, +, -, or @strong> as a formula. The example’s protection option prefixes those data values with a tab inside a quoted field. That mitigation changes the cell data, so it is not universally safe for every spreadsheet or importer. Disable it only when exact raw values are required and the destination treats every cell as inert text.
Validate row counts, column counts, and data types
A successful parse does not prove that the selected record boundary or column mapping is correct. Compare the generated CSV with representative source records before replacing a production export.
- Record count: The number of CSV data rows should equal the number of elements matched by the selected qualified name.
- Column count: The header should contain the complete first-seen field union, including fields that appear only in later records.
- Repeated values: Inspect cells containing compact JSON arrays and confirm that their order and count match the source child elements.
- Value spelling: Dates, numbers, leading zeros, identifiers, and Booleans remain text spellings from XML, but a spreadsheet may still guess their types when the file is opened.
- Encoding: The Java output is UTF-8 without a byte-order mark. Some spreadsheet configurations still require an import wizard or an explicit UTF-8 selection.
Use controlled column types when identifiers, leading zeros, dates, or high-precision numbers must survive the spreadsheet import unchanged.
Handle XML shapes that need custom logic
The DOM approach is appropriate for a predictable collection of records. It does not infer records automatically, expand nested arrays into several rows, join parent values into descendants, evaluate XPath, normalize namespaces, validate against an XSD, or preserve schema types. Nested element boundaries, child attributes, comments, processing instructions, structural prefixes, and mixed-content ordering are also outside the mapping.
Arbitrary XML should therefore be converted with an explicit XSLT transformation or application-specific Java code. For very large documents, a DOM parser loads the complete tree into memory; a StAX or SAX implementation can process records incrementally while retaining the same carefully defined record and column rules.
Preflight the mapping in a local browser
For a manageable feed, the XML to CSV Converter can provide an independent browser-based preflight for the same XML-to-CSV mapping without replacing the Java implementation.
- Paste the well-formed XML and enter the exact qualified name shared by the repeating record elements.
- Keep formula protection on for a spreadsheet intended for human review, convert the document, and verify the record and column counts.
- Copy or download the CSV, inspect repeated-child JSON cells and type-sensitive values, and compare the result against the source.
The browser utility parses and converts locally through DOMParser, so the document is not uploaded. Malformed tags, quoting, or entities block conversion, and DOCTYPE declarations are rejected before parsing; external entities, DTD defaults, and custom entity definitions are not processed. The W3C DOM Parsing and Serialization specification documents the browser API used for this workflow.
The converter fails rather than truncating beyond its limits of 500,000 XML characters, 10,000 matching records, 200 columns, and 5,000,000 CSV characters. Its downloaded file uses UTF-8 text/csv without adding a byte-order mark. Use this browser check to confirm the record name and mapping before finalizing or running the corresponding Java pipeline.
If you're weighing options, XML JSON Converter: Mapping Rules and Workflow covers this in detail.