转换前:
wangjj23转换后:
wangjj
23
代码:
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("
wangjj23");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();
}
}
分享到:
2012-08-02 14:21
浏览 8519
评论