Adding linebreak in xml file before root node

前端 未结 5 2632
庸人自扰
庸人自扰 2021-02-20 01:41

I am trying to add line break after my comments above the root node in XML document.

I need something like this:



        
5条回答
  •  Happy的楠姐
    2021-02-20 02:43

    Revisiting this after some time because I had the same issue. I found another solution that does not need to buffer the output in a String:

    1. Write only the XML-declaration by passing an empty document. This will also append a linebreak.

    2. Write the document content without XML-declaration

    Code:

    StreamResult streamResult = new StreamResult(writer);
    // output XML declaration with an empty document
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.transform(new DOMSource(), streamResult);
    // output the document without XML declaration
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(new DOMSource(doc), streamResult);
    

提交回复
热议问题