zoukankan      html  css  js  c++  java
  • 字符串对象跟xml格式的转换

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


    xml string document 之间的转换
    -- XML String字符串  转  XML Document文档
    String  strXml = /"....../";
    Document document = DocumentHelper.parseText(strXml);
    
    
    
    -- XML Document文档  转  XML String字符串
    Document document = ...;
    String strXml= document.asXML();
    
    
    
    
    
  • 相关阅读:
    linux oracle命令行窗口命令上下翻阅
    oracle 转移表空间
    perl字符集处理
    Perl解析JSON数据精解
    处理外壳PROC
    FileIsExe
    写壳前的设计
    SEH结构化异常处理03
    SEH结构化异常处理02
    博客首记
  • 原文地址:https://www.cnblogs.com/Soy-technology/p/11648601.html
Copyright © 2011-2022 走看看