How to get a formatted XML file with TransformerFactory?

Z

Zsolt

Hi,

I use the code below (jdk-1.4.2-06) to write into XML files. How can I get
an indented output like below:

<top>
<sub>Hello</sub>
<sub2>Hello2</sub2>
<sub3>
<sub4>Hello3</sub4>
</sub3>
</top>

DOMSource source = new DOMSource(root);
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
Properties props = new Properties();
props.setProperty(OutputKeys.ENCODING, "UTF-8");
props.setProperty(OutputKeys.METHOD, "xml");
props.setProperty(OutputKeys.INDENT, "yes");

transformer.setOutputProperties(props);

StringWriter ascii = new StringWriter();
StreamResult result = new StreamResult(ascii);
transformer.transform(source, result);

Zsolt
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top