转换前: <Head><name>wangjj</name><age>23</age></Head>
转换后:

<?xml version="1.0" encoding="gb2312"?>

<Head>
  <name>wangjj</name>
  <age>23</age>
</Head>

代码:

package com.sun.ATest;

import java.io.StringWriter;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class XmlFormat {
   //字符串 XML 格式化处理
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  try {
   String temp = new XmlFormat().formatXml("<Head><name>wangjj</name><age>23</age></Head>");
   System.out.println(temp);
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 public static String formatXml(String str) throws Exception {
  Document document = null;
  document = DocumentHelper.parseText(str);
  // 格式化输出格式
  OutputFormat format = OutputFormat.createPrettyPrint();
  format.setEncoding("gb2312");
  StringWriter writer = new StringWriter();
  // 格式化输出流
  XMLWriter xmlWriter = new XMLWriter(writer, format);
  // 将document写入到输出流
  xmlWriter.write(document);
  xmlWriter.close();

  return writer.toString();
 }
}

posted on 2014-04-02 09:24  帅的惊动了党  阅读(10378)  评论(0编辑  收藏  举报