java 구현된 xml 포맷 구현 코드
3205 단어 xml 포맷
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 도구는 이 코드를 사용하는 것입니다.