import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import org.jdom2.Document;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
/**
* 读取一个xml文件返回string
*
* @author lmb
*
*/
public class MyXmlUtil {
/**
* 加载xml文件
*
* @return Document
* @throws IOException
* @throws JDOMException
*/
public static Document load(InputStream fileurl) throws JDOMException, IOException {
Document document = null;
SAXBuilder reader = new SAXBuilder();
InputStreamReader read = new InputStreamReader(fileurl);
document = reader.build(read);
return document;
}
/**
* 将xml文件转换为String串
*
* @return
* @throws IOException
* @throws JDOMException
*/
public static String XmlToString(InputStream fileurl) throws IOException, JDOMException {
Document document = null;
document = load(fileurl);
Format format = Format.getPrettyFormat();
format.setEncoding("UTF-8");// 设置编码格式
StringWriter out = null; // 输出对象
String sReturn = ""; // 输出字符串
XMLOutputter outputter = new XMLOutputter(format);
out = new StringWriter();
outputter.output(document, out);
sReturn = out.toString();
return sReturn;
}
}
java dom2解析XMl返回String 串
于 2021-10-29 16:52:29 首次发布