Exception
public
static
String formatXml(String str)
throws
Exception {
Document document
=
null
;
document
=
DocumentHelper.parseText(str);
//
格式化输出格式
OutputFormat format =
OutputFormat.createPrettyPrint();
format.setEncoding(
"UTF-8"
);
StringWriter writer
=
new
StringWriter();
//
格式化输出流
XMLWriter xmlWriter =
new
XMLWriter(writer, format);
//
将document写入到输出流
xmlWriter.write(document);
xmlWriter.close();
return
writer.toString();
* 将xml文件转换成字符串对象
*
@param
fileName 文件名(需要位置对应)
*
@return
public
String xmlChangeString(String fileName) {
try
{
SAXReader saxReader
=
new
SAXReader();
//
新建一个解析类
//
Document tempDocument = saxReader.read(XmlUtil.class.getClassLoader().getResourceAsStream(fileName));
//
读入一个文件
Document tempDocument = saxReader.read(
new
File(fileName));
return
tempDocument.asXML();
}
catch
(DocumentException e) {
e.printStackTrace();
return
null
;
//
public static void main(String [] args) throws Exception{
//
String test = "<Head><name>wangsong</name><age>24</age></Head>";
//
System.out.println(formatXml(test));
}
xml string document 之间的转换
-- XML String字符串 转 XML Document文档
String strXml = /"....../";
Document document = DocumentHelper.parseText(strXml);
-- XML Document文档 转 XML String字符串
Document document = ...;
String strXml= document.asXML();