您的位置:首页 > 编程语言 > Java开发

java 读取xml文件,并转换成字符串

2012-05-09 15:39 218 查看
packagecom.sfzc.books.service.imp;importjava.io.File;importjava.io.IOException;importjava.io.StringWriter;importjava.net.URL;importorg.jdom.input.SAXBuilder;importorg.jdom.output.Format;importorg.jdom.output.XMLOutputter;importcom.sfzc.relation.service.imp.ProPropertiesOperate;publicclassGetXml{privateStringfileUrl=null;publicStringgetFileUrl(){returnfileUrl;}publicGetXml(Stringfile){this.fileUrl=GetXml.getPath(file);}/***获得项目所在路径*@returnString*/publicstaticStringgetPath(Stringfilename){URLurl=GetXml.class.getResource("");Filefile=newFile(url.getFile());Stringpath=file.getParent();while(-1!=path.lastIndexOf("bin")||-1!=path.lastIndexOf(".jar")){file=newFile(path);path=file.getParent();}if(path.startsWith("file")){path=path.replaceAll("file:","");}path=path+File.separator+"imp\\"+filename;path="C:\\ProgramFiles\\ApacheSoftwareFoundation\\Tomcat5.5\\webapps\\sfzc\\WEB-INF\\classes\\com\\sfzc\\books\\service\\imp\\"+filename;returnpath;}publicorg.jdom.Documentload(){org.jdom.Documentdocument=null;Stringurl=this.getFileUrl();try{SAXBuilderreader=newSAXBuilder();document=reader.build(newFile(url));}catch(Exceptione){e.printStackTrace();}returndocument;}publicStringXmlToString(){org.jdom.Documentdocument=null;document=this.load();Formatformat=Format.getPrettyFormat();format.setEncoding("UTF-8");//设置编码格式StringWriterout=null;//输出对象StringsReturn="";//输出字符串XMLOutputteroutputter=newXMLOutputter();out=newStringWriter();try{outputter.output(document,out);}catch(IOExceptione){e.printStackTrace();}sReturn=out.toString();returnsReturn;}}
实例化与调用:
StringstrXml=null;GetXmlxml=newGetXml("General.xml");strXml=xml.XmlToString();returnstrXml;

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: