亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

java用dom更新xml的問題,怎么在子節點下添加節點?

java用dom更新xml的問題,怎么在子節點下添加節點?

幕布斯6054654 2018-12-07 04:36:14
有原始xml如下: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <students> <student> <name sn="03" sn2="0322"/> </student> </students> 我想要得到修改后的結果為: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <students> <student> <name sn="03" sn2="0322"/> <name sn="04" sn2="0422"/> </student> </students> 我的代碼為: public static void main(String[] args) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse("D:/students.xml"); Element eltName = doc.createElement("name"); Attr attr = doc.createAttribute("sn"); attr.setValue("04"); Attr attr2 = doc.createAttribute("sn2"); attr2.setValue("0422"); eltName.setAttributeNode(attr); eltName.setAttributeNode(attr2); Element eltRoot=doc.getDocumentElement(); eltRoot.appendChild(eltName); doc2XmlFile(doc, "D:/students.xml"); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 將Document對象修改后寫入到xml里面 * @param document Document對象 * @param filename xml文件路徑 * @return */ public boolean doc2XmlFile(Document document, String filename) { boolean flag = true; try { /** 將document中的內容寫入文件中 */ TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); /** 編碼 */ transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); DOMSource source = new DOMSource(document); StreamResult result = new StreamResult(new File(filename)); transformer.transform(source, result); } catch (Exception ex) { flag = false; System.out.println("更新" + filename + "出錯:" + ex); log.error("更新" + filename + "出錯:" + ex); ex.printStackTrace(); } return flag; } 這樣得到的結果為: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <students> <student> <name sn="03" sn2="0322"/> </student> <name sn="04" sn2="0422"/> </students> 弄了一天了也沒能把添加的name節點放到student節點下面,請教各位大俠了! ? ? ? ? ? ? ? ?
查看完整描述

2 回答

  • 2 回答
  • 0 關注
  • 934 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號