Home >Java >javaTutorial >How to Format an Unformatted XML String in Java Using JAXP and DOM?

How to Format an Unformatted XML String in Java Using JAXP and DOM?

DDD
DDDOriginal
2024-12-18 01:11:17499browse

How to Format an Unformatted XML String in Java Using JAXP and DOM?

Formatting an XML String in Java

As a Java developer, you may encounter situations where you have an XML string with no line feeds or indentations and need to convert it into a nicely formatted string. This is particularly useful for debugging purposes or presenting XML data in a readable manner.

To accomplish this task, you can leverage the Java API for XML Processing (JAXP) and the Document Object Model (DOM) to transform the XML string into a formatted representation.

Firstly, create a new Transformer object from the TransformerFactory. Set the "INDENT" and "{http://xml.apache.org/xslt}indent-amount" properties to "yes" and "2" respectively, to enable line breaks and indentations:

Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

Next, convert the XML string into a DOMSource object:

String inputXml = "<tag><nested>hello</nested></tag>";
DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(inputXml))));

Then, create a StreamResult object to hold the formatted XML string:

StreamResult result = new StreamResult(new StringWriter());

Finally, transform the source DOM into the formatted XML string using the transformer:

transformer.transform(source, result);

The result.getWriter() object will contain the formatted XML string:

String formattedXml = result.getWriter().toString();

Example:

String unformattedXml = "hello";
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
DOMSource source = new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(unformattedXml))));

StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
System.out.println(result.getWriter().toString());

Output:

<?xml version="1.0" encoding="UTF-8"?>
<tag>
  <nested>hello</nested>
</tag>

The above is the detailed content of How to Format an Unformatted XML String in Java Using JAXP and DOM?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn