java用dom更新xml的问题,怎么在子节点下添加节点?
有原始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>
Element eltRoot=doc.getDocumentElement();//获取根节点
eltRoot.appendChild(eltName);//将新的节点拼接到根节点
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<students>
<student>
<name sn="03" sn2="0322"/>
</student>
<name sn="04" sn2="0422"/>
</students>
Element eltRoot=doc.getDocumentElement();
NodeList list = eltRoot.getChildNodes();
if (list != null) {
for (int i = 0; i < list.getLength(); i++) {
if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
list.item(i).appendChild(eltName);
}
}
}