在javascript中将节点添加到xml文件中

Adding nodes to xml file in javascript

本文关键字:xml 添加 文件 节点 javascript      更新时间:2023-09-26

我正在尝试使用javascript向xml文件添加一个条目。下面的代码应该将一个名为book的节点添加到此文件中。但它根本不起作用。我还尝试了一些其他代码,只是为了更改xml数据库中的一个条目,但也没有成功。那我的错在哪里呢?

代码:

function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
    xhttp=new XMLHttpRequest();
}
else {
    xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("database.xml");
newNode = xmlDoc.createElement("entry");
newNode.nodeValue = "aaaaa";
x=xmlDoc.documentElement;
x.appendChild(newNode);

XML FILE(database.XML):

<?xml version="1.0" encoding="ISO-8859-1"?>
<database>
<entry>
    <title>Everyday Italian</title>
    <content>Strange. I seem to get hungry about the same time every day!</content>
    <time>August 7, 2012, 6:24 PM</time>
    <comment>Giada De Laurentiis</comment>
</entry>
<entry>
    <title>I'm Hungry</title>
    <content>I really need something to eat!!</content>
    <time>August 7, 2012, 6:24 PM</time>
    <comment>Giada De Laurentiis</comment>
</entry>
</database>

您正在通过网络读取XML文件,我猜您正在通过添加新节点来修改MEMORY中的XML文档。但是,您的代码中没有任何内容可以将修改后的XML文件从内存保存到持久介质中。您可以实现POST或PUT方法来写入文件,就像您实现GET方法来读取文件一样。当然,您的web服务器应该配置为接受这样的PUT请求并覆盖原始文件。