有原始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节点下面,请教各位大侠了!
Element eltRoot=doc.getDocumentElement();
你的这里获取到的是students节点撒。
如果想添加到student下的话,还要往里一层了。
改成下面就好了
Node eltRoot = doc.getDocumentElement() .getElementsByTagName("student").item(0); eltRoot.appendChild(eltName);