关于用dom4j生成xml后第二行空行的问题

来源:互联网 发布:哪里可以购买淘宝店铺 编辑:程序博客网 时间:2024/06/06 20:24

之前碰到这个问题,困扰了我很久没解决.百度了一下很少.所以刚解决就来给大家分享一下

package one;import java.io.FileOutputStream;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import org.dom4j.io.OutputFormat;import org.dom4j.io.XMLWriter;public class Xml {public static void main(String[] args) {// TODO Auto-generated method stubDocument document = DocumentHelper.createDocument();Element root = document.addElement("EnglishWords");// root.addComment("This is a test for dom4j ");Element singleWord = root.addElement("EnglishWord");Element word = singleWord.addElement("word");Element englishMean = singleWord.addElement("englishMean");Element chineseMean = singleWord.addElement("chineseMean");Element attribute = singleWord.addElement("attribute");Element example = singleWord.addElement("example");// 添加元素内容word.addText("1");attribute.addText("2");chineseMean.addText("3");englishMean.addText("4");example.addText("5");// 添加属性// singleWord.addAttribute("code", "1");OutputFormat format = OutputFormat.createPrettyPrint();format.setEncoding("UTF-8");format.setNewLineAfterDeclaration(false); format.setIndent(true);try {String filename = "F:/Users/luxiangyu/Desktop/a.xml";FileOutputStream out = new FileOutputStream(filename);//XMLWriter writer = new XMLWriter(out, format);document.setXMLEncoding("UTF-8");writer.write(document);out.close();} catch (Exception e) {e.printStackTrace();}} }
最关键的就是format.setNewLineAfterDeclaration(false);这句话,因为默认是true,要设置一下改为false

这个方法是设置声明之后换不换行的

1 0
原创粉丝点击