Philipp Braun
Philipp Braun

Reputation: 1573

Adding nodes to xml file in javascript

I am trying to add an entry to a xml file using javascript. The code below is supposed to add a node called book to this file. But it simply doesn't work. I have also tried some other code just to change an entry in the xml database, but also without success. So what is my fault?

CODE:

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>

Upvotes: 0

Views: 1155

Answers (1)

Boluc Papuccuoglu
Boluc Papuccuoglu

Reputation: 2346

You are reading an XML file through the network, and I am guessing that you ARE modifying the XML document which is in MEMORY by adding a new node. But there is nothing in your code that would save the modified XML file from memory to a persistable medium. You could implement a POST or PUT method to write the file just as you implemented the GET method to read it. Of course, your web server should be configured to take such a PUT request and overwrite the original file.

Upvotes: 1

Related Questions