4

I am trying to write a XML file with proper indentation. Here is my code:

   public class WebVideo {

 private final String C_XMLFILEPATH = "resources/video.xml";
 private String itemId;
 private String videoPath;

 public WebVideo(long itemId, String videoPath) {
  this.itemId = Long.toString(itemId);
  this.videoPath = videoPath;
 }

 public void saveVideo() throws ParserConfigurationException, IOException,
   TransformerFactoryConfigurationError, TransformerException,
   SAXException {
  File xmlFile = new File(C_XMLFILEPATH);
  DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory
    .newInstance();
  DocumentBuilder documentBuilder = documentBuilderFactory
    .newDocumentBuilder();
  Document document = null;
  Element rootElement = null;

  if (xmlFile.exists()) {
   document = documentBuilder.parse(xmlFile);
   rootElement = document.getDocumentElement();

  } else {
   document = documentBuilder.newDocument();
   rootElement = document.createElement("Videos");
   document.appendChild(rootElement);
  }

  Element itemElement = document.createElement("Video");
  rootElement.appendChild(itemElement);

  Element idElement = document.createElement("Id");
  Text id = document.createTextNode(itemId);
  idElement.appendChild(id);
  itemElement.appendChild(idElement);

  Element pathElement = document.createElement("Path");
  Text path = document.createTextNode(videoPath);
  pathElement.appendChild(path);
  itemElement.appendChild(pathElement);

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

  StreamResult streamResult = new StreamResult(new StringWriter());
  DOMSource domSource = new DOMSource(document);
  transformer.transform(domSource, streamResult);
  String xmlString = streamResult.getWriter().toString();

  BufferedWriter bufferedWriter = new BufferedWriter(
    new OutputStreamWriter(new FileOutputStream(xmlFile)));
  bufferedWriter.write(xmlString);
  bufferedWriter.flush();
  bufferedWriter.close();
 }
}

Everything is okay, but If you see carefully the output XML file there is a problem when I append a new element. The output XML file is here:

  <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <Videos>
        <Video>
            <Id>1</Id>
            <Path>path</Path>
        </Video>
    <Video>
            <Id>2</Id>
            <Path>path</Path>
        </Video>
    </Videos>

The tag is in the same indent with tag. How can I solve this problem? Thank you.

Harry Joy
  • 58,650
  • 30
  • 162
  • 207
Tapas Bose
  • 28,796
  • 74
  • 215
  • 331
  • Possible duplicate of [How to pretty print XML from Java?](http://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) – ThomasRS Dec 16 '15 at 14:43

4 Answers4

3

Check this answer for pretty printing of XML: How to pretty print XML from Java?

Community
  • 1
  • 1
Steve
  • 53,375
  • 33
  • 96
  • 141
2

You can also create your own linebreak format if you want more customization. Append the linebreak text before you append the actual child:

Text lineBreak = doc.createTextNode("\n\t");

element.appendChild(lineBreak);
Kazi Islam
  • 135
  • 1
  • 2
  • 9
1
public String formatXML(String input)
{
    try
    {
        final InputSource src = new InputSource(new StringReader(input));
        final Node document = DocumentBuilderFactory.newInstance()
                .newDocumentBuilder().parse(src).getDocumentElement();

        final DOMImplementationRegistry registry = DOMImplementationRegistry
                .newInstance();
        final DOMImplementationLS impl = (DOMImplementationLS) registry
                .getDOMImplementation("LS");
        final LSSerializer writer = impl.createLSSerializer();

        writer.getDomConfig().setParameter("format-pretty-print",
                Boolean.TRUE);
        writer.getDomConfig().setParameter("xml-declaration", true);

        return writer.writeToString(document);
    } catch (Exception e)
    {
        e.printStackTrace();
        return input;
    }
}
NIDHEESH KRISHNA
  • 147
  • 1
  • 1
  • 10
1

Some XML libraries have pretty print functionality built in. For example dom4j has OutputFormat.createPrettyPrint() - see a guide on how to use it at http://dom4j.sourceforge.net/dom4j-1.6.1/guide.html#Writing_a_document_to_a_file

Qwerky
  • 18,217
  • 6
  • 44
  • 80