文檔對象模型(DOM)是處理完備文檔與複雜應用的標準,提供極大靈活性,實現完整且穩定,眾多大型安裝選擇它正是為避免API變更導致大量重寫。然而,DOM從設計之初即為語言無關模型,傾向於C、Perl等語言,未充分利用Java的面向對象特性,實際使用中難免遇到諸多不便。本文針對以XML作為數據傳輸統一格式及UI展示接口的場景,總結DOM使用心得。
初期即預判會遇到困難,因此建立簡單工具類封裝DOM對象的公共方法,事後證明極為明智。若每次創建Document對象都需編寫5行以上代碼並處理煩人的異常,極大打擊開發積極性。XMLTool類封裝了以下核心方法:
每個方法均捕獲相關DOM異常並轉為RuntimeException拋出。實際上這些異常(如ParserConfigurationException、TransformerConfigurationException)極少發生,一旦發生通常意味著系統環境配置問題(如缺少解析器包),無法在代碼層面處理,故僅簡要獲取錯誤信息拋出。
/** 初始化空Document對象 */
public static Document newXMLDocument() {
try {
return newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
throw new RuntimeException(e.getMessage());
}
}
/** 初始化DocumentBuilder */
public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {
return newDocumentBuilderFactory().newDocumentBuilder();
}
/** 初始化DocumentBuilderFactory,啟用命名空間感知 */
public static DocumentBuilderFactory newDocumentBuilderFactory() {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
return dbf;
}
/** 將XML字符串解析為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());
}
}
/** 從輸入流解析Document對象 */
public static Document parseXMLDocument(InputStream is) {
try {
return newDocumentBuilder().parse(is);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
此封裝大幅減少樣板代碼,讓開發者專注於業務邏輯,提升代碼可維護性與團隊協作效率。