Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I want to create an xml file with line breaks, looking somewhat like this:

<Instrument currencyId="THB"
disabledCount="0"
hasBeenEnabledOnce="TRUE"
</Instrument>

Using this code I got close but all attributes seems to be end up on the same row:

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.newDocument();

Element rootElement = doc.createElement("Instrument");
doc.appendChild(rootElement);

Instrument.setAttribute("currencyId", "THB");
Instrument.setAttribute("disabledCount", "0");
Instrument.setAttribute("hasBeenEnabledOnce", "TRUE");

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File("C:\\file.xml"));
    transformer.transform(source, result);

I get the following result:

<Instrument currencyId="THB" disabledCount="0" hasBeenEnabledOnce="TRUE"

How can I add linebreaks between the attributes??

just a slight notice, I thought that transformer.setOutputProperies could solve the problem, by searching for similar problems I ended up with "OutputKeys.INDENT", "yes", and the indent-amount -> "4". But nothing's changed. Doesnt matter if I open the file in notepad++ or as a webpage.

share|improve this question
    
Your XML is not well-formed. Please correct it (looks like a missing ">" but only you can know) –  peter.murray.rust Jun 12 '13 at 12:20
    
That was not really my question but yeah, there is a ">" missing after "TRUE", should be there, I just missed it when copying from my code. My question on the other hand is about, if its possible to make a line break between "currencyId="THB"" and "disabledCount="0"" so that it looks like the intended code above? –  Magnus Glannefors Jun 12 '13 at 13:36
    
It wasn't clear where you want the end tag, or whether you wish to use the "/>" construct or whether there was content which might have been omitted. In general formatting inside start tags is normally dependent on your toolchain - you may have to subclass the serialization class(es) –  peter.murray.rust Jun 12 '13 at 14:52

1 Answer 1

I would suggest you to once refer this link while working on XML and line breaks.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.