【发布时间】:2015-07-28 04:44:06
【问题描述】:
我正在正确读取一个 xml 文件,但我无法写入它。
这是文件:键值设置的配置文件。
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<setting key="Password" value="d92e1dedba95d2cf00d4c567e57e3342"/>
<setting key="ExceptionFileLog" value="exception.txt"/>
<setting key="ActionFileLog" value="actions.txt" />
<setting key="ShowInfoMessage" value="false" />
</configuration>
我使用 javax.xml.parsers.DocumentBuilder 正确打开和读取文件:
private Document _doc = null;
public XmlConfig(String filePath) throws Exception
{
File xml = new File(filePath);
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
_doc = dBuilder.parse(xml);
_doc.getDocumentElement().normalize();
}
到目前为止一切顺利,但我无法写入和持久化对文件的更改:
public boolean updateValue(String key, String value)
{
NodeList settlist = _doc.getElementsByTagName(SETTNAME);
for(int i = 0; i < settlist.getLength(); i++)
{
Element sett = (Element) settlist.item(i);
if(sett.getNodeType() == Node.ELEMENT_NODE)
{
if(null != sett.getAttribute("key") && sett.getAttribute("key").equals(key))
{
sett.setAttribute("value", value);
return true;
}
}
}
return false;
}
所以,如果我从 _doc(文档对象)打印 xml 文件,更改会正确写入,但 xml 文件不会更新!
我想我正在内存中打开、读取和写入 xml 文件,我需要一种方法来将更改保留在磁盘上。 我不知道,任何建议将不胜感激。
【问题讨论】:
-
您没有存储 xml 文件..所有更改都保留在内存中..