我到处寻找这个问题,但无法弄清楚发生了什么。
我尝试做的是在检查节点时将某些内容附加到XML文件的末尾,以确保其中没有该节点。因此,如果我想添加到XML文件中但已经存在,那么它就不会写入。
我遇到的问题是它会追加到最后,但无论节点是否存在,它都会成功。因此,如果我运行这5次,我最终会将它添加五次而不是一次。我的代码如下:
public void writeSettingsFile(String file, String keyIn, String contentIn)
{
try {
String filepath = file;
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
docFactory.setIgnoringComments(true);
docFactory.setIgnoringElementContentWhitespace(true);
DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
Document doc = docBuilder.parse(filepath);
Node settings = doc.getElementsByTagName("Settings").item(0);
NodeList list = settings.getChildNodes();
Element newSetting = doc.createElement(keyIn);
newSetting.appendChild(doc.createTextNode(contentIn));
for (int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
System.out.println(i);
System.out.println(node.getNodeName());
if (!keyIn.equals(node.getNodeName()) && !hasWhiteSpace(node))
{
settings.appendChild(newSetting);
System.out.println("This should be written");
System.out.println("Not written");
}
else
{
System.out.println("Not written");
}
}
// write the content into xml file
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new File(filepath));
transformer.transform(source, result);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
} catch (TransformerException tfe) {
tfe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (SAXException sae) {
sae.printStackTrace();
}
}
答案 0 :(得分:0)
好的我已经弄明白了,我改变了循环,我创建了一个布尔变量来保存是否找到了密钥。默认情况下设置为false,它会扫描密钥,如果找到它,则将keyFound更改为true,然后不会写入我们的新密钥,如果未找到它将保持为false,这将写入我们的密钥。代码发布在下面。
Boolean keyFound = false;
for (int i = 0; i < list.getLength(); i++)
{
Node node = list.item(i);
System.out.println(i);
System.out.println(node.getNodeName());
if (keyIn.equals(node.getNodeName()))
{
keyFound = true;
System.out.println("Found");
}
}
System.out.println("All keys scanned");
if (keyFound == false)
{
settings.appendChild(newSetting);
System.out.println("Written");
}