Adding linebreak in xml file before root node

前端 未结 5 2737
庸人自扰
庸人自扰 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条回答
  •  不知归路
    2021-02-20 02:26

    You can achieve this by not adding the comment node to your document, but instead partially transforming your document. First transform your own XML processing instruction and comment separately, and then the rest of document:

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new FileInputStream(new File("abc.xml")));
    
    Result output = new StreamResult(new File("abc.xml"));
    Source input = new DOMSource(doc);
    
    
    // xml processing instruction and comment node
    ProcessingInstruction xmlpi = doc.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"");
    Comment comment = doc.createComment("DO NOT EDIT THIS FILE");
    
    // first transform the processing instruction and comment
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.transform(new DOMSource(xmlpi), output);
    transformer.transform(new DOMSource(comment), output);
    // then the document
    transformer.transform(input, output);
    

提交回复
热议问题