相关文章推荐
礼貌的凳子  ·  pyqtgraph:在使用TimeAxisI ...·  1 年前    · 
八块腹肌的盒饭  ·  C# 中的.pdb/ ...·  1 年前    · 
沉稳的烈马  ·  set_xticks和set_xtickla ...·  1 年前    · 
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)); }


xml string document 之间的转换
-- XML String字符串  转  XML Document文档
String  strXml = /"....../";
Document document = DocumentHelper.parseText(strXml);
-- XML Document文档  转  XML String字符串
Document document = ...;
String strXml= document.asXML();