解析XML文件流为字符串


将XML文件内容解析为一个字符串。

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class T {
	public static void main(String[] args) {
		String path = getPath("111.xml");
		String strXml = XmlToString(path);
		System.out.println(strXml);
	}

	/** 
	  * 获得项目所在路径 
	  * @return String 
	  */
	public static String getPath(String filename) {
		String path = "E:" + File.separator + filename;
		return path;
	}

	public static org.jdom.Document load(String path) {
		org.jdom.Document document = null;
		try {
			SAXBuilder reader = new SAXBuilder();
			document = reader.build(new File(path));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return document;
	}

	public static String XmlToString(String path) {
		org.jdom.Document document = null;
		document = load(path);

		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;
	}

}

你可能感兴趣的:(解析xml)