DOM4j处理XML文件时,写入文件后发现XML文件很多空行,而且文件也变大了,我现在是用XML文件来传输数据,不知道怎么处理这种问题.

解决方案 »

  1.   

    我现在是通过XML来传输数据,经常对一个XML文件中的某些值进行修改,每次修改保存后就产生了很多空行,XML文件也随之变大,时间长了肯定不行了。
      

  2.   

    Format format = Format.getCompactFormat();
    format.setEncoding("utf-8");
    format.setIndent("         ");
    XMLOutputter XMLOut = new XMLOutputter(format);
    XMLOut.output(Doc, new FileOutputStream(xmlname));
      

  3.   

    楼上用的是XMLOutputter 是JDOM包,我用的是DOM4J不能混用,JDOM里面貌似没有设置缩进格式的方法。
      

  4.   

    DOM4J也可以
    Document document = DocumentHelper.createDocument();
    XMLWriter writer = null;
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("UTF-8");
    format.setExpandEmptyElements(true);
    format.setTrimText(false);
    format.setIndent(" ");
      

  5.   

    http://javaprogram.5d6d.com/blog.php?tid=628 /**
                     * 通过 org.dom4j.io.OutputFormat 来设置XML文档输出格式
                     */
                    OutputFormat format = OutputFormat.createPrettyPrint(); // 设置XML文档输出格式
                    format.setEncoding("UTF-8"); // 设置XML文档的编码类型
                    format.setSuppressDeclaration(true);
                    format.setIndent(true);      // 设置是否缩进
                    format.setIndent("   ");     // 以空格方式实现缩进
                    format.setNewlines(true);    // 设置是否换行                try {
                            /** 将document中的内容写入文件中 */
                            XMLWriter writer = new XMLWriter(new FileWriter(new File(
                                            xmlFileName)), format);
                            writer.write(this.getDocument());
                            writer.close();
                    } catch (Exception ex) {
                            System.out.println(ex.getMessage());
                    }
      

  6.   

    郁闷,现在有遇到新问题了,这种方式写入XML文件后文件就变成0字节了,我不知道是不是Document对象实例化的问题,这是几行关键代码,为什么一执行XML文件就成0字节了。File xmlFile = new File("D:\\Tomcat4.1\\webapps\\demostate\\test.xml");
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(xmlFile);
    .
    .
    .
    .
    .
    FileWriter fw = new FileWriter(xmlFile);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding("GBK");
    format.setExpandEmptyElements(true);
    format.setTrimText(false);
    format.setIndent(" ");XMLWriter xmlw = new XMLWriter(fw,format);
    xmlw.write(doc);xmlw.flush();
    xmlw.close();
      

  7.   

    已经处理完毕,完全使用DOM4J可以,原来的错误原因可能是混用了不同的解析XML的包导致的。多谢各位的回答!
      

  8.   

    想问一下这个Format是哪个包下的了?是java.text.Format吗?我用的是jdom,怎么引用进去后说方法都不存在啊