package com.sunshen.jfids.testWebService.task; import java.io.File; import java.io.StringWriter; import com.sunsheen.jfids.dom4j.Document; import com.sunsheen.jfids.dom4j.DocumentException; import com.sunsheen.jfids.dom4j.DocumentHelper; im
package com.sunshen.jfids.testWebService.task; import java.io.File; import java.io.StringWriter; import com.sunsheen.jfids.dom4j.Document; import com.sunsheen.jfids.dom4j.DocumentException; import com.sunsheen.jfids.dom4j.DocumentHelper; import com.sunsheen.jfids.dom4j.io.OutputFormat; import com.sunsheen.jfids.dom4j.io.SAXReader; import com.sunsheen.jfids.dom4j.io.XMLWriter; /** * 字符串对象跟xml格式的转换 * @author WangSong * */ public class XmlFormat { /** * 将字符串格式化成xml * @param str * @return * @throws 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)); // } }