第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

java用dom更新xml的問題,怎么在子節(jié)點(diǎn)下添加節(jié)點(diǎn)?

java用dom更新xml的問題,怎么在子節(jié)點(diǎn)下添加節(jié)點(diǎn)?

幕布斯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> 我想要得到修改后的結(jié)果為: <?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中的內(nèi)容寫入文件中 */ 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 + "出錯(cuò):" + ex); log.error("更新" + filename + "出錯(cuò):" + ex); ex.printStackTrace(); } return flag; } 這樣得到的結(jié)果為: <?xml version="1.0" encoding="UTF-8" standalone="no"?> <students> <student> <name sn="03" sn2="0322"/> </student> <name sn="04" sn2="0422"/> </students> 弄了一天了也沒能把添加的name節(jié)點(diǎn)放到student節(jié)點(diǎn)下面,請教各位大俠了! ? ? ? ? ? ? ? ?
查看完整描述

2 回答

  • 2 回答
  • 0 關(guān)注
  • 933 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)