posts - 495,  comments - 11,  trackbacks - 0

            文檔對象模型 (DOM) 是一個文檔標準,對于完備的文檔和復雜的應用程序,DOM 提供了大量靈活性。DOM標準是標準的。它很強壯且完整,并且有許多實現。這是許多大型安裝的決定因素--特別是對產品應用程序,以避免在API發生改變時進行大量的改寫。

            以上是我在選擇處理XML數據時之所以沒有選擇JDOM或者dom4j等其它面向對象的標準的原因,不過也由于DOM從一開始就是一種與語言無關的模型,而且它更趨向用于像C或Perl這類語言,沒有利用Java的面向對象的性能,所以在使用的過程中也遇到了不少的麻煩,今天這里做一個小結。另外,我目前使用XML主要是作為數據傳輸的統一格式,并統一用戶界面展示的接口,應用的面并不是很廣,所以使用到的DOM的內容其實不多。

            在準備使用它的時候,是做了充足的準備的,也有遇到困難的準備,所以一開始就有了一個簡單的工具類來封裝DOM對象使用時必要的公共方法,實際證明這樣做是很明智的,一個簡單的創建Document對象的操作,要是每次都需要寫上5行以上代碼,并且還要處理那些煩人的Exception,實在是會打擊大家的積極性,所以在最初,做了一個XMLTool類,專門封裝了如下的公共方法:

            1、 Document對象創建(包括空的Document對象創建,以一個給定Node節點作為根節點創建。

            2、 將一個規范的XML字符串轉換成一個Document對象。

            3、 從物理硬盤讀取一個XML文件并返回一個Document對象。

            4、 將一個Node對象轉換成字符串。

            其中每個方法都截獲相關的DOM操作所拋出的異常,轉換成一個RuntimeException拋出,這些異常在實際使用過程中,一般狀況下其實都不會拋出,特別是象生成一個Document對象時的ParserConfigurationException、轉換Node節點成字符串時要生成一個Transformer對象時的TransformerConfigurationException等等,沒有必要在它們身上花時間精力。而且真就出了相關的異常的話,其實根本沒有辦法處理,這樣的狀況通常是系統環境配置有問題(比如必要的DOM實現解析器等包沒有加入環境),所以包裝該異常時只是很簡要的獲取其Message拋出。

            代碼如下:

          /**
          * 初始化一個空Document對象返回。
          * @return a Document
          */
          public static Document newXMLDocument() {
           try {
            return newDocumentBuilder().newDocument();
           } catch (ParserConfigurationException e) {
             throw new RuntimeException(e.getMessage());
           }
          }
          /**
          * 初始化一個DocumentBuilder
          * @return a DocumentBuilder
          * @throws ParserConfigurationException
          */
          public static DocumentBuilder newDocumentBuilder()
          throws ParserConfigurationException {
          return newDocumentBuilderFactory().newDocumentBuilder();
          }
          /**
          * 初始化一個DocumentBuilderFactory
          * @return a DocumentBuilderFactory
          */
          public static DocumentBuilderFactory newDocumentBuilderFactory() {
           DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
           dbf.setNamespaceAware(true);
           return dbf;
          }
          /**
          * 將傳入的一個XML String轉換成一個org.w3c.dom.Document對象返回。
          * @param xmlString 一個符合XML規范的字符串表達。
          * @return a Document
          */
          public static Document parseXMLDocument(String xmlString) {
           if (xmlString == null) {
            throw new IllegalArgumentException();
           }
           try {
            return newDocumentBuilder().parse(
             new InputSource(new StringReader(xmlString)));
           } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
           }
          }
          /**
          * 給定一個輸入流,解析為一個org.w3c.dom.Document對象返回。
          * @param input
          * @return a org.w3c.dom.Document
          */
          public static Document parseXMLDocument(InputStream input) {
           if (input == null) {
            throw new IllegalArgumentException("參數為null!");
           }
           try {
            return newDocumentBuilder().parse(input);
           } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
           }
          }
          /**
          * 給定一個文件名,獲取該文件并解析為一個org.w3c.dom.Document對象返回。
          * @param fileName 待解析文件的文件名
          * @return a org.w3c.dom.Document
          */
          public static Document loadXMLDocumentFromFile(String fileName) {
           if (fileName == null) {
            throw new IllegalArgumentException("未指定文件名及其物理路徑!");
           }
           try {
            return newDocumentBuilder().parse(new File(fileName));
           } catch (SAXException e) {
            throw new IllegalArgumentException("目標文件(" + fileName + ")不能被正確解析為XML!
          " + e.getMessage());
           } catch (IOException e) {
            throw new IllegalArgumentException("不能獲取目標文件(" + fileName + ")!
          " + e.getMessage());
           } catch (ParserConfigurationException e) {
            throw new RuntimeException(e.getMessage());
           }
          }
          /**
          * 給定一個節點,將該節點加入新構造的Document中。
          * @param node a Document node
          * @return a new Document
          */
          public static Document newXMLDocument(Node node) {
           Document doc = newXMLDocument();
           doc.appendChild(doc.importNode(node, true));
           return doc;
          }
          /**
          * 將傳入的一個DOM Node對象輸出成字符串。如果失敗則返回一個空字符串""。
          * @param node DOM Node 對象。
          * @return a XML String from node
          */
          public static String toString(Node node) {
           if (node == null) {
            throw new IllegalArgumentException();
           }
           Transformer transformer = newTransformer();
           if (transformer != null) {
            try {
             StringWriter sw = new StringWriter();
             transformer.transform(new DOMSource(node),
              new StreamResult(sw));
              return sw.toString();
            } catch (TransformerException te) {
             throw new RuntimeException(te.getMessage());
            }
           }
           return errXMLString("不能生成XML信息!");
          }
          /**
          * 將傳入的一個DOM Node對象輸出成字符串。如果失敗則返回一個空字符串""。
          * @param node DOM Node 對象。
          * @return a XML String from node
          */
          public static String toString(Node node) {
           if (node == null) {
            throw new IllegalArgumentException();
           }
           Transformer transformer = newTransformer();
           if (transformer != null) {
            try {
             StringWriter sw = new StringWriter();
             transformer.transform(new DOMSource(node),new StreamResult(sw));
             return sw.toString();
            } catch (TransformerException te) {
              throw new RuntimeException(te.getMessage());
            }
           }
           return errXMLString("不能生成XML信息!");
          }
          /**
          * 獲取一個Transformer對象,由于使用時都做相同的初始化,所以提取出來作為公共方法。
          * @return a Transformer encoding gb2312
          */
          public static Transformer newTransformer() {
           try {
            Transformer transformer =TransformerFactory.newInstance().newTransformer();
            Properties properties = transformer.getOutputProperties();
            properties.setProperty(OutputKeys.ENCODING, "gb2312");
            properties.setProperty(OutputKeys.METHOD, "xml");
            properties.setProperty(OutputKeys.VERSION, "1.0");
            properties.setProperty(OutputKeys.INDENT, "no");
            transformer.setOutputProperties(properties);
            return transformer;
           } catch (TransformerConfigurationException tce) {
            throw new RuntimeException(tce.getMessage());
           }
          }
          /**
          * 返回一段XML表述的錯誤信息。提示信息的TITLE為:系統錯誤。之所以使用字符串拼裝,主要是這樣做一般
          * 不會有異常出現。
          * @param errMsg 提示錯誤信息
          * @return a XML String show err msg
          */
          public static String errXMLString(String errMsg) {
           StringBuffer msg = new StringBuffer(100);
           msg.append("<?xml version="1.0" encoding="gb2312" ?>");
           msg.append("<errNode title="系統錯誤" errMsg="" + errMsg + ""/>");
           return msg.toString();
          }
          /**
          * 返回一段XML表述的錯誤信息。提示信息的TITLE為:系統錯誤
          * @param errMsg 提示錯誤信息
          * @param errClass 拋出該錯誤的類,用于提取錯誤來源信息。
          * @return a XML String show err msg
          */
          public static String errXMLString(String errMsg, Class errClass) {
           StringBuffer msg = new StringBuffer(100);
           msg.append("<?xml version="1.0" encoding="gb2312" ?>");
           msg.append("<errNode title="系統錯誤" errMsg=""+ errMsg
            + "" errSource=""
            + errClass.getName()
            + ""/>");
           return msg.toString();
          }
          /**
          * 返回一段XML表述的錯誤信息。
          * @param title 提示的title
          * @param errMsg 提示錯誤信息
          * @param errClass 拋出該錯誤的類,用于提取錯誤來源信息。
          * @return a XML String show err msg
          */
          public static String errXMLString(
           String title,
           String errMsg,
           Class errClass) {
            StringBuffer msg = new StringBuffer(100);
            msg.append("<?xml version="1.0" encoding="gb2312" ?>");
            msg.append("<errNode title=""
             + title
             + "" errMsg=""
             + errMsg
             + "" errSource=""
             + errClass.getName()
             + ""/>");
            return msg.toString();
           }

          posted on 2007-08-20 02:22 jadmin 閱讀(90) 評論(0)  編輯  收藏

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 潍坊市| 习水县| 漯河市| 承德县| 濉溪县| 盖州市| 边坝县| 秦皇岛市| 博白县| 嘉峪关市| 新营市| 大埔县| 甘谷县| 共和县| 永川市| 乐至县| 元阳县| 筠连县| 荣成市| 上栗县| 栾城县| 久治县| 遂宁市| 巴林右旗| 怀来县| 梓潼县| 长春市| 澄江县| 汾西县| 济源市| 大埔区| 静安区| 小金县| 玉门市| 长兴县| 嘉鱼县| 迭部县| 礼泉县| 西宁市| 兴仁县| 郯城县|