往xml中更新節點的實例代碼
/* 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("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(source, result);*/
以上這篇往xml中更新節點的實例代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。