当前位置:编程学习 > JAVA >>

写入到xml文件的排版问题



 boolean exist = file.exists();
DocumentBuilderFactory domFactory = DocumentBuilderFactory
.newInstance();
domFactory.setIgnoringComments(true);
DocumentBuilder builder = domFactory.newDocumentBuilder();
Document doc = null;
if (exist) {
doc = builder.parse(file);
} else {
doc = builder.newDocument();
Element root = doc.createElement("Log");
doc.appendChild(root);
}
Element logTag = doc.createElement("LogTag");
Element timeValue = doc.createElement("Time");
Element msgValue = doc.createElement("Message");
Text time = doc.createTextNode(param.createTime);
Text message = doc.createTextNode(param.logMessage);
timeValue.appendChild(time);
msgValue.appendChild(message);
logTag.appendChild(timeValue);
logTag.appendChild(msgValue);
doc.getDocumentElement().appendChild(logTag);

if (!exist) {
TransformerFactory transformerFactory = TransformerFactory
.newInstance();
// step10:获得一个Transformer对象
Transformer transformer = transformerFactory.newTransformer();
// step11:把document对象用一个DOMSource对象包装起来
Source xmlSource = new DOMSource(doc);
// step12:建立一个存储目标对象
Result outputTarget = new StreamResult(file);
// step13:生成相应的xml文件
transformer.transform(xmlSource, outputTarget);
}else{
DOMSource source = new DOMSource(doc);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        StreamResult result = new StreamResult(file.getAbsolutePath());
        transformer.transform(source, result);
}


代码如上,查看xml文件,没有换行,没有排版,可读性非常差,请教大神,有什么办法可以解决这个问题 --------------------编程问答-------------------- 国庆期间,打扰大家,非常抱歉。自己帮自己顶一个 --------------------编程问答-------------------- 你自己看节点在哪结束  加个回车呗 --------------------编程问答-------------------- 在输入流里每行后面加个换行符,应该就可以了吧 --------------------编程问答-------------------- 两个方法:一个如楼上所说,换行符,另一个可以去下个开源的code beautiful jar包 构建完以后的xml调用jar包方法格式化一下 --------------------编程问答--------------------  代码不好实现吧,,既然需要自己来看,就放到eclipse  ctrl+shift+F 格式化,,, --------------------编程问答-------------------- 我会告诉你dom4j有这个功能? --------------------编程问答-------------------- /*
 * 功能:写入xml文件
 */
public  static void write2kml(Document document){
try{ 
        OutputFormat format = new OutputFormat("",true);//定义格式
        format.setEncoding("UTF-8");
        format.setTrimText(false);

            XMLWriter formatWriter = new XMLWriter(new FileOutputStream(new File(filePath)),format);
            formatWriter.write(document);
            formatWriter.close();
            
          }catch(Exception ex){ 
           ex.printStackTrace();
              log.debug("写入xml文件失败"); 
          } 
 }
补充:Java ,  Java SE
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,