欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现的xml格式化实现代码

程序员文章站 2024-03-11 15:17:19
核心代码: package com.ddatsh; import java.io.ioexception; import java.io.stringr...

核心代码:

package com.ddatsh;
 
import java.io.ioexception;
import java.io.stringreader;
import java.io.stringwriter;
import java.io.unsupportedencodingexception;
 
import org.dom4j.document;
import org.dom4j.documentexception;
import org.dom4j.io.outputformat;
import org.dom4j.io.saxreader;
import org.dom4j.io.xmlwriter;
 
public class xmlformat {
 
  public static string format(string str) throws exception {
    saxreader reader = new saxreader();
    // system.out.println(reader);
    // 注释:创建一个串的字符输入流
    stringreader in = new stringreader(str);
    document doc = reader.read(in);
    // system.out.println(doc.getrootelement());
    // 注释:创建输出格式
    outputformat formater = outputformat.createprettyprint();
    //formater=outputformat.createcompactformat();
    // 注释:设置xml的输出编码
    formater.setencoding("utf-8");
    // 注释:创建输出(目标)
    stringwriter out = new stringwriter();
    // 注释:创建输出流
    xmlwriter writer = new xmlwriter(out, formater);
    // 注释:输出格式化的串到目标中,执行后。格式化后的串保存在out中。
    writer.write(doc);
 
    writer.close();
    system.out.println(out.tostring());
    // 注释:返回我们格式化后的结果
    return out.tostring();
  }
 
  public static void main(string[] args) throws exception {
    string head="<?xml version=\"1.0\" encoding=\"gbk\"?>";
    string str = "<requestdata><headdata><usercode>sh1_admin</usercode><username>sh1_admin</username><usercompanycode>3107</usercompanycode><usercompanyname>上海分公司一部</usercompanyname><requesttype>03</requesttype></headdata><bodydata><reportid>113100000033</reportid><insurant>a5rfg87</insurant><numberplate>沪e78612</numberplate><enginemodel></enginemodel><carvin></carvin><accidentdate>2011-02-25 15:07:00</accidentdate><reportdate>2011-02-25 15:07:00</reportdate><province>310000</province><city>310100</city><district></district><accidentplace>1</accidentplace><accidentlongitude></accidentlongitude><accidentlatitude></accidentlatitude><surveylongitude></surveylongitude><surveylatitude></surveylatitude><scenereportflag></scenereportflag><reporter></reporter><reportertel></reportertel><surveyplace></surveyplace><operatorid>3525</operatorid><operatorname>sh_admin</operatorname><reportdealid>30000800</reportdealid><reportdealname>江苏分公司</reportdealname><companyname></companyname><customertypecode></customertypecode><forcepolicyid>a5rfg87a5rfg87a5rfg87</forcepolicyid><bizpolicyid></bizpolicyid><index>0</index><fieldname>5</fieldname></bodydata></requestdata>";
    // system.out.println(str);
    format(str);
  }
 
}

oschina用的在线格式化xml的工具就是使用此段代码。