DOM方式进行的XML文件、Document、String之间的相互转换

XML文件test.xml:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?><books><book><name>哈里波特</name><price>10</price><memo>这是一本很好看的书。</memo></book></books>  
 

java代码:

Java代码   收藏代码
  1. import java.io.*;  
  2. import java.net.URI;  
  3.   
  4. import javax.xml.parsers.*;  
  5. import javax.xml.transform.*;  
  6. import javax.xml.transform.dom.DOMSource;  
  7. import javax.xml.transform.stream.StreamResult;  
  8.   
  9. import org.w3c.dom.Document;  
  10. import org.xml.sax.InputSource;  
  11.   
  12. import com.sun.org.apache.xml.internal.serialize.*;  
  13.   
  14. /** 
  15.  * DOM方式操作XML 
  16.  *  
  17.  * @author Watson Xu 
  18.  * @date 2011-5-3 上午09:49:27 
  19.  */  
  20. public class OperateXMLByDOM {  
  21.     /** 
  22.      * 将给定文件的内容或者给定 URI 的内容解析为一个 XML 文档,并且返回一个新的 DOM Document 对象 
  23.      *  
  24.      * @param filePath 文件所在路径 
  25.      * @return DOM的Document对象 
  26.      * @throws Exception 
  27.      */  
  28.     public static Document xml2Doc(String filePath) {  
  29.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  30.         DocumentBuilder builder = null;  
  31.         FileInputStream inputStream = null;  
  32.         Document doc = null;  
  33.         try {  
  34.             builder = factory.newDocumentBuilder();  
  35.   
  36.             /* 通过文件方式读取,注意文件保存的编码和文件的声明编码要一致(默认文件声明是UTF-8) */  
  37.             File file = new File(filePath);  
  38.             doc = builder.parse(file);  
  39.   
  40.             /* 通过一个URL方式读取 */  
  41.             URI uri = new URI(filePath);//filePath="http://java.sun.com/index.html"  
  42.             doc = builder.parse(uri.toString());  
  43.   
  44.             /* 通过java IO 流的读取 */  
  45.             inputStream = new FileInputStream(filePath);  
  46.             doc = builder.parse(inputStream);  
  47.             return doc;  
  48.         } catch (Exception e) {  
  49.             return null;  
  50.         } finally {  
  51.             if (inputStream != null) {  
  52.                 try {  
  53.                     inputStream.close();  
  54.                 } catch (IOException e) {  
  55.                     return null;  
  56.                 }  
  57.             }  
  58.         }  
  59.     }  
  60.   
  61.     /** 
  62.      * Document 转换为 String 并且进行了格式化缩进 
  63.      *  
  64.      * @param doc XML的Document对象 
  65.      * @return String 
  66.      */  
  67.     public static String doc2FormatString(Document doc) {         
  68.         StringWriter stringWriter = null;  
  69.         try {  
  70.             stringWriter = new StringWriter();  
  71.             if(doc != null){  
  72.                 OutputFormat format = new OutputFormat(doc,"UTF-8",true);  
  73.                 //format.setIndenting(true);//设置是否缩进,默认为true  
  74.                 //format.setIndent(4);//设置缩进字符数  
  75.                 //format.setPreserveSpace(false);//设置是否保持原来的格式,默认为 false  
  76.                 //format.setLineWidth(500);//设置行宽度  
  77.                 XMLSerializer serializer = new XMLSerializer(stringWriter,format);  
  78.                 serializer.asDOMSerializer();  
  79.                 serializer.serialize(doc);  
  80.                 return stringWriter.toString();  
  81.             } else {  
  82.                 return null;  
  83.             }  
  84.         } catch (Exception e) {  
  85.             return null;  
  86.         } finally {  
  87.             if(stringWriter != null){  
  88.                 try {  
  89.                     stringWriter.close();  
  90.                 } catch (IOException e) {  
  91.                     return null;  
  92.                 }  
  93.             }  
  94.         }  
  95.     }  
  96.       
  97.     /** 
  98.      * Document 转换为 String 
  99.      *  
  100.      * @param doc XML的Document对象 
  101.      * @return String 
  102.      */  
  103.     public static String doc2String(Document doc){  
  104.         try {  
  105.             Source source = new DOMSource(doc);  
  106.             StringWriter stringWriter = new StringWriter();  
  107.             Result result = new StreamResult(stringWriter);  
  108.             TransformerFactory factory = TransformerFactory.newInstance();  
  109.             Transformer transformer = factory.newTransformer();  
  110.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
  111.             transformer.transform(source, result);  
  112.             return stringWriter.getBuffer().toString();  
  113.         } catch (Exception e) {  
  114.             return null;  
  115.         }  
  116.     }  
  117.   
  118.     /** 
  119.      * String 转换为 Document 对象 
  120.      *  
  121.      * @param xml 字符串 
  122.      * @return Document 对象 
  123.      */  
  124.     public static Document string2Doc(String xml) {  
  125.         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();  
  126.         DocumentBuilder builder = null;  
  127.         Document doc = null;  
  128.         InputSource source = null;  
  129.         StringReader reader = null;  
  130.         try {  
  131.             builder = factory.newDocumentBuilder();  
  132.             reader = new StringReader(xml);  
  133.             source = new InputSource(reader);//使用字符流创建新的输入源  
  134.             doc = builder.parse(source);  
  135.             return doc;  
  136.         } catch (Exception e) {  
  137.             return null;  
  138.         } finally {  
  139.             if(reader != null){  
  140.                 reader.close();  
  141.             }  
  142.         }  
  143.     }  
  144.   
  145.     /** 
  146.      * Document 保存为 XML 文件 
  147.      *  
  148.      * @param doc Document对象 
  149.      * @param path 文件路径 
  150.      */  
  151.     public static void doc2XML(Document doc, String path) {  
  152.         try {  
  153.             Source source = new DOMSource(doc);  
  154.             Result result = new StreamResult(new File(path));  
  155.             Transformer transformer = TransformerFactory.newInstance().newTransformer();  
  156.             transformer.setOutputProperty(OutputKeys.INDENT, "yes");  
  157.             transformer.transform(source, result);  
  158.         } catch (Exception e) {  
  159.             return;  
  160.         }  
  161.     }  
  162.   
  163.     public static void main(String[] args) {  
  164.         Document doc = xml2Doc("test.xml");  
  165.         System.out.println(doc);  
  166.         System.out.println(doc2String(doc));  
  167.         System.out.println(doc2FormatString(doc));  
  168.         doc = string2Doc(doc2FormatString(doc));  
  169.         doc2XML(doc, "1.xml");  
  170.     }  
  171. }  
 

 

输出的XML文件1.xml:

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8" standalone="no"?>  
  2. <books>  
  3.     <book>  
  4.         <name>哈里波特</name>  
  5.         <price>10</price>  
  6.         <memo>这是一本很好看的书。</memo>  
  7.     </book>  
  8. </books>  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值