DIV CSS 佈局教程網

Java 操作 XML:動態更新節點的實例代碼
編輯:AJAX基礎知識     

本文分享一段使用 Java 向 XML 文件更新(追加)節點的實例代碼,涉及 DOM 解析與 Transformer 持久化的完整流程。

 /* System.out.println("2323"); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder docbuilder = factory.newDocumentBuilder(); Document parse = docbuilder .parse(new File("src/ProdQuery.xml")); // Element createElement2 = parse.createElement(""); Element createElement = parse.createElement("products"); Node item2 = parse.getChildNodes().item(parse.getChildNodes().getLength()-1); for (String item : map.keySet()) { //循環添加至 products System.out.println("tianjia1"); Element clidren = parse.createElement("product"); Attr createAttribute = parse.createAttribute("name"); createAttribute.setNodeValue(item); Attr createAttribute2 = parse.createAttribute("value"); createAttribute2.setNodeValue(map.get(item)); clidren.setAttributeNode(createAttribute); clidren.setAttributeNode(createAttribute2); createElement.appendChild(clidren); } //將 products 添加到根目錄 item2.appendChild(createElement); //創建一個 TransformerFactory 對象 TransformerFactory tFactory = TransformerFactory.newInstance(); //得到一個操作對象 Transformer transformer = tFactory.newTransformer(); //設置編碼 transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(parse); System.out.println("改變文件"); StreamResult result = new StreamResult(new File("src/ProdQuery.xml")); //讓 xml 文件換行 transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{https://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result);*/

這段代碼的核心思路是:先解析加載目標 XML 文檔,遍歷數據循環創建 product 子節點並掛到 products 容器上,最後通過 Transformer 設置好編碼與縮進格式,把修改後的文檔寫回原文件。以上就是本次 XML 節點更新的實例分享,希望能給大家一個參考。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved