Format XML in Java

Thing you want to do


<tag><tag>test</tag></tag>

A string like


<tag>
  <tag>test</tag>
</tag>

I want to convert it like this.

Method

There seem to be various theories about how to do it, but I combined some of them as follows.


	static public String formatXml(String xml) {

		try {

			InputStream bais = new ByteArrayInputStream(xml.getBytes("utf-8"));

			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document doc = builder.parse(bais);
			doc.setXmlStandalone(true);

			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
			StreamResult result = new StreamResult(new StringWriter());
			DOMSource source = new DOMSource(doc);
			transformer.transform(source, result);
			String xmlString = result.getWriter().toString();
			String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
			return header + "\n" + xmlString;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return xml;
	}

Recommended Posts

Format XML in Java
Implement XML signature in Java
google java format
Partization in Java
Rock-paper-scissors in Java
Pi in Java
FizzBuzz in Java
Output Notes document as XML document in Java
Try using JSON format API in Java
Output Date in Java in ISO 8601 extended format
Java that outputs vmg format file in eml format
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Callable Interface in Java
Azure functions in java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
webApi memorandum in java
Type determination in Java
Ping commands in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
Java Gold Countermeasures: Format
POST JSON in Java
Express failure in Java
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Try using RocksDB in Java
Read binary files in Java 1
Get EXIF information in Java
Save Java PDF in Excel
[Neta] Sleep Sort in Java
Java history in this world
Let Java segfault in 6 lines
Try calling JavaScript in Java
Try developing Spresense in Java (1)
Try functional type in Java! ①
I made roulette in Java.
Create hyperlinks in Java PowerPoint
Refactoring: Make Blackjack in Java
Write flyway callbacks in Java
Topic Analysis (LDA) in Java
Importing Excel data in Java 2