我是java应用程序的新开发人员。我想修改 XML 文件节点值。我使用了xml文件进行修改如下
<staff id="2">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>2000000</salary>
<age>28</age>
</staff>
在上面的 xml 中,我想将工资值更改为 345375。对于此修改,我编写了如下代码
try{
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(new File("/sdcard/myxml.xml"));
//Get the staff element by tag name directly
Node nodes = doc.getElementsByTagName("staff").item(0);
//loop the staff child node
NodeList list = nodes.getChildNodes();
for (int i =0; i<list.getLength();i++){
Node node = list.item(i);
//get the salary element, and update the value
if("salary".equals(node.getNodeName())){
node.setNodeValue("345375");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
如果我使用这种方式,那么价值不会修改薪水。
如何修改 XML 节点值?
首先你必须意识到node.setValue()
正在修改存储的表示在记忆中。知道了这一点,您只需要弄清楚如何将该输出写入磁盘即可。看this http://xerces.apache.org/xerces2-j/faq-dom.html#faq-3,举个例子。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)