java jdomxml 换行_jdom处理的XML Document 和String 之间的相互转化

packageutil;importjava.io.ByteArrayOutputStream;importjava.io.File;importjava.io.FileWriter;importjava.io.StringReader;importorg.jdom.Document;importorg.jdom.input.SAXBuilder;importorg.jdom.output.Format;importorg.jdom.output.XMLOutputter;/*** JDOM 方式操作XML

*

*@authorWatson Xu

* @date 2011-5-3 下午02:20:49*/

public classOperationXMLByJdom {/*** DOCUMENT格式化输出保存为XML

*

*@paramdoc JDOM的Document

*@paramfilePath 输出文件路径

*@throwsException*/

public static void doc2XML(Document doc, String filePath) throwsException{

Format format=Format.getCompactFormat();

format.setEncoding("UTF-8"); //设置XML文件的字符为UTF-8

format.setIndent(" ");//设置缩进

XMLOutputter outputter= new XMLOutputter(format);//定义输出 ,在元素后换行,每一层元素缩排四格

FileWriter writer = new FileWriter(filePath);//输出流

outputter.output(doc, writer);

writer.close();

}/*** 字符串转换为DOCUMENT

*

*@paramxmlStr 字符串

*@returndoc JDOM的Document

*@throwsException*/

public static Document string2Doc(String xmlStr) throwsException {

java.io.Reader in= newStringReader(xmlStr);

Document doc= (newSAXBuilder()).build(in);returndoc;

}/*** Document转换为字符串

*

*@paramxmlFilePath XML文件路径

*@returnxmlStr 字符串

*@throwsException*/

public static String doc2String(Document doc) throwsException {

Format format=Format.getPrettyFormat();

format.setEncoding("UTF-8");//设置xml文件的字符为UTF-8,解决中文问题

XMLOutputter xmlout = newXMLOutputter(format);

ByteArrayOutputStream bo= newByteArrayOutputStream();

xmlout.output(doc, bo);returnbo.toString();

}/*** XML转换为Document

*

*@paramxmlFilePath XML文件路径

*@returndoc Document对象

*@throwsException*/

public static Document xml2Doc(String xmlFilePath) throwsException {

File file= newFile(xmlFilePath);return (newSAXBuilder()).build(file);

}public static voidmain(String[] args) {try{

Document doc= xml2Doc("test.xml");

System.out.println(doc);

System.out.println(doc2String(doc));

doc=string2Doc(doc2String(doc));

doc2XML(doc,"1.xml");

}catch(Exception e) {

e.printStackTrace();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值