java xml子节点_java用dom更新xml的问题,怎么在子节点下添加节点?

有原始xml如下:

我想要得到修改后的结果为:

我的代码为:

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;

}

这样得到的结果为:

弄了一天了也没能把添加的name节点放到student节点下面,请教各位大侠了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值