笔记-将XML文件读取为String字符串
import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.net.URL; import org.jdom.input.SAXBuilder; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** * 读取XML文件,转成String字符串 */ public class ReadXmlToString { private String fileUrl = null; public String getFileUrl() { return fileUrl; } public ReadXmlToString(String path) { this.fileUrl = path; } public org.jdom.Document load() { org.jdom.Document document = null; String url = this.getFileUrl(); try { SAXBuilder reader = new SAXBuilder(); document = reader.build(new File(url)); } catch (Exception e) { e.printStackTrace(); } return document; } public String XmlToString() { org.jdom.Document document = null; document = this.load(); Format format = Format.getPrettyFormat(); format.setEncoding("UTF-8");//设置编码格式 StringWriter out = null; //输出对象 String sReturn = ""; //输出字符串 XMLOutputter outputter = new XMLOutputter(); out = new StringWriter(); try { outputter.output(document, out); } catch (IOException e) { e.printStackTrace(); } sReturn = out.toString(); return sReturn; } public static void main(String[] args) { String strXml = null; ReadXmlToString xml = new ReadXmlToString("C:\\Program Files (x86)\\iVS-100\\iVS-100-Server\\iVS_Storage\\FileZilla Server.xml"); strXml = xml.XmlToString(); System.out.println(strXml); } }