org.w3c.dom document 和xml 字符串 互转

[html]  view plain  copy
  1. package com.mymhotel.opera;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.StringReader;  
  7. import java.io.StringWriter;  
  8. import java.util.Properties;  
  9.   
  10. import javax.xml.parsers.DocumentBuilder;  
  11. import javax.xml.parsers.DocumentBuilderFactory;  
  12. import javax.xml.parsers.ParserConfigurationException;  
  13. import javax.xml.transform.OutputKeys;  
  14. import javax.xml.transform.Transformer;  
  15. import javax.xml.transform.TransformerConfigurationException;  
  16. import javax.xml.transform.TransformerException;  
  17. import javax.xml.transform.TransformerFactory;  
  18. import javax.xml.transform.dom.DOMSource;  
  19. import javax.xml.transform.stream.StreamResult;  
  20.   
  21. import org.w3c.dom.Document;  
  22. import org.w3c.dom.Node;  
  23. import org.xml.sax.InputSource;  
  24. import org.xml.sax.SAXException;  
  25.   
  26. public class DOMUtils {  
  27.     /**  
  28.      * 初始化一个空Document对象返回。  
  29.      *  
  30.      * @return a Document  
  31.      */  
  32.     public static Document newXMLDocument() {  
  33.         try {  
  34.             return newDocumentBuilder().newDocument();  
  35.         } catch (ParserConfigurationException e) {  
  36.             throw new RuntimeException(e.getMessage());  
  37.         }  
  38.     }  
  39.   
  40.     /**  
  41.      * 初始化一个DocumentBuilder  
  42.      *  
  43.      * @return a DocumentBuilder  
  44.      * @throws ParserConfigurationException  
  45.      */  
  46.     public static DocumentBuilder newDocumentBuilder()  
  47.             throws ParserConfigurationException {  
  48.         return newDocumentBuilderFactory().newDocumentBuilder();  
  49.     }  
  50.   
  51.     /**  
  52.      * 初始化一个DocumentBuilderFactory  
  53.      *  
  54.      * @return a DocumentBuilderFactory  
  55.      */  
  56.     public static DocumentBuilderFactory newDocumentBuilderFactory() {  
  57.         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
  58.         dbf.setNamespaceAware(true);  
  59.         return dbf;  
  60.     }  
  61.   
  62.     /**  
  63.      * 将传入的一个XML String转换成一个org.w3c.dom.Document对象返回。  
  64.      *  
  65.      * @param xmlString  
  66.      *            一个符合XML规范的字符串表达。  
  67.      * @return a Document  
  68.      */  
  69.     public static Document parseXMLDocument(String xmlString) {  
  70.         if (xmlString == null) {  
  71.             throw new IllegalArgumentException();  
  72.         }  
  73.         try {  
  74.             return newDocumentBuilder().parse(  
  75.                     new InputSource(new StringReader(xmlString)));  
  76.         } catch (Exception e) {  
  77.             throw new RuntimeException(e.getMessage());  
  78.         }  
  79.     }  
  80.   
  81.     /**  
  82.      * 给定一个输入流,解析为一个org.w3c.dom.Document对象返回。  
  83.      *  
  84.      * @param input  
  85.      * @return a org.w3c.dom.Document  
  86.      */  
  87.     public static Document parseXMLDocument(InputStream input) {  
  88.         if (input == null) {  
  89.             throw new IllegalArgumentException("参数为null!");  
  90.         }  
  91.         try {  
  92.             return newDocumentBuilder().parse(input);  
  93.         } catch (Exception e) {  
  94.             throw new RuntimeException(e.getMessage());  
  95.         }  
  96.     }  
  97.   
  98.     /**  
  99.      * 给定一个文件名,获取该文件并解析为一个org.w3c.dom.Document对象返回。  
  100.      *  
  101.      * @param fileName  
  102.      *            待解析文件的文件名  
  103.      * @return a org.w3c.dom.Document  
  104.      */  
  105.     public static Document loadXMLDocumentFromFile(String fileName) {  
  106.         if (fileName == null) {  
  107.             throw new IllegalArgumentException("未指定文件名及其物理路径!");  
  108.         }  
  109.         try {  
  110.             return newDocumentBuilder().parse(new File(fileName));  
  111.         } catch (SAXException e) {  
  112.             throw new IllegalArgumentException("目标文件(" + fileName  
  113.                     + ")不能被正确解析为XML!" + e.getMessage());  
  114.         } catch (IOException e) {  
  115.             throw new IllegalArgumentException("不能获取目标文件(" + fileName + ")!"  
  116.                     + e.getMessage());  
  117.         } catch (ParserConfigurationException e) {  
  118.             throw new RuntimeException(e.getMessage());  
  119.         }  
  120.     }  
  121.   
  122.     /*  
  123.      * 把dom文件转换为xml字符串  
  124.      */  
  125.     public static String toStringFromDoc(Document document) {  
  126.         String result = null;  
  127.   
  128.         if (document != null) {  
  129.             StringWriter strWtr = new StringWriter();  
  130.             StreamResult strResult = new StreamResult(strWtr);  
  131.             TransformerFactory tfac = TransformerFactory.newInstance();  
  132.             try {  
  133.                 javax.xml.transform.Transformer t = tfac.newTransformer();  
  134.                 t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");  
  135.                 t.setOutputProperty(OutputKeys.INDENT, "yes");  
  136.                 t.setOutputProperty(OutputKeys.METHOD, "xml"); // xml, html,  
  137.                 // text  
  138.                 t.setOutputProperty(  
  139.                         "{http://xml.apache.org/xslt}indent-amount", "4");  
  140.                 t.transform(new DOMSource(document.getDocumentElement()),  
  141.                         strResult);  
  142.             } catch (Exception e) {  
  143.                 System.err.println("XML.toString(Document): " + e);  
  144.             }  
  145.             result = strResult.getWriter().toString();  
  146.             try {  
  147.                 strWtr.close();  
  148.             } catch (IOException e) {  
  149.                 e.printStackTrace();  
  150.             }  
  151.         }  
  152.   
  153.         return result;  
  154.     }  
  155.   
  156.     /**  
  157.      * 给定一个节点,将该节点加入新构造的Document中。  
  158.      *  
  159.      * @param node  
  160.      *            a Document node  
  161.      * @return a new Document  
  162.      */  
  163.   
  164.     public static Document newXMLDocument(Node node) {  
  165.         Document doc = newXMLDocument();  
  166.         doc.appendChild(doc.importNode(node, true));  
  167.         return doc;  
  168.     }  
  169.   
  170.     /**  
  171.      * 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。  
  172.      *  
  173.      * @param node  
  174.      *            DOM Node 对象。  
  175.      * @return a XML String from node  
  176.      */  
  177.   
  178.     /*  
  179.      * public static String toString(Node node) { if (node == null) { throw new  
  180.      * IllegalArgumentException(); } Transformer transformer = new  
  181.      * Transformer(); if (transformer != null) { try { StringWriter sw = new  
  182.      * StringWriter(); transformer .transform(new DOMSource(node), new  
  183.      * StreamResult(sw)); return sw.toString(); } catch (TransformerException  
  184.      * te) { throw new RuntimeException(te.getMessage()); } } return ""; }  
  185.      */  
  186.   
  187.     /**  
  188.      * 将传入的一个DOM Node对象输出成字符串。如果失败则返回一个空字符串""。  
  189.      *  
  190.      * @param node  
  191.      *            DOM Node 对象。  
  192.      * @return a XML String from node  
  193.      */  
  194.   
  195.     /*  
  196.      * public static String toString(Node node) { if (node == null) { throw new  
  197.      * IllegalArgumentException(); } Transformer transformer = new  
  198.      * Transformer(); if (transformer != null) { try { StringWriter sw = new  
  199.      * StringWriter(); transformer .transform(new DOMSource(node), new  
  200.      * StreamResult(sw)); return sw.toString(); } catch (TransformerException  
  201.      * te) { throw new RuntimeException(te.getMessage()); } } return ""; }  
  202.      */  
  203.   
  204.     /**  
  205.      * 获取一个Transformer对象,由于使用时都做相同的初始化,所以提取出来作为公共方法。  
  206.      *  
  207.      * @return a Transformer encoding gb2312  
  208.      */  
  209.   
  210.     public static Transformer newTransformer() {  
  211.         try {  
  212.             Transformer transformer = TransformerFactory.newInstance()  
  213.                     .newTransformer();  
  214.             Properties properties = transformer.getOutputProperties();  
  215.             properties.setProperty(OutputKeys.ENCODING, "gb2312");  
  216.             properties.setProperty(OutputKeys.METHOD, "xml");  
  217.             properties.setProperty(OutputKeys.VERSION, "1.0");  
  218.             properties.setProperty(OutputKeys.INDENT, "no");  
  219.             transformer.setOutputProperties(properties);  
  220.             return transformer;  
  221.         } catch (TransformerConfigurationException tce) {  
  222.             throw new RuntimeException(tce.getMessage());  
  223.         }  
  224.     }  
  225.   
  226.     /**  
  227.      * 返回一段XML表述的错误信息。提示信息的TITLE为:系统错误。之所以使用字符串拼装,主要是这样做一般 不会有异常出现。  
  228.      *  
  229.      * @param errMsg  
  230.      *            提示错误信息  
  231.      * @return a XML String show err msg  
  232.      */  
  233.     /*  
  234.      * public static String errXMLString(String errMsg) { StringBuffer msg = new  
  235.      * StringBuffer(100);  
  236.      * msg.append("<?xml version="1.0" encoding="gb2312" ?>");  
  237.      * msg.append("<errNode title="系统错误" errMsg="" + errMsg + ""/>"); return  
  238.      * msg.toString(); }  
  239.      */  
  240.     /**  
  241.      * 返回一段XML表述的错误信息。提示信息的TITLE为:系统错误  
  242.      *  
  243.      * @param errMsg  
  244.      *            提示错误信息  
  245.      * @param errClass  
  246.      *            抛出该错误的类,用于提取错误来源信息。  
  247.      * @return a XML String show err msg  
  248.      */  
  249.     /*  
  250.      * public static String errXMLString(String errMsg, Class errClass) {  
  251.      * StringBuffer msg = new StringBuffer(100);  
  252.      * msg.append("<?xml version='1.0' encoding='gb2312' ?>");  
  253.      * msg.append("<errNode title="  
  254.      * 系统错误" errMsg=""+ errMsg + "" errSource=""+ errClass.getName()+ ""/>");  
  255.      *  return msg.toString(); }  
  256.      */  
  257.     /**  
  258.      * 返回一段XML表述的错误信息。  
  259.      *  
  260.      * @param title  
  261.      *            提示的title  
  262.      * @param errMsg  
  263.      *            提示错误信息  
  264.      * @param errClass  
  265.      *            抛出该错误的类,用于提取错误来源信息。  
  266.      * @return a XML String show err msg  
  267.      */  
  268.   
  269.     public static String errXMLString(String title, String errMsg,  
  270.             Class errClass) {  
  271.         StringBuffer msg = new StringBuffer(100);  
  272.         msg.append("<?xml version='1.0' encoding='utf-8' ?>");  
  273.         msg.append("<errNode title=" + title + "errMsg=" + errMsg  
  274.                 + "errSource=" + errClass.getName() + "/>");  
  275.         return msg.toString();  
  276.     }  
  277.   
  278. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值