I seem to be stuck in implementing an "XML data insert using Javascript".
My application is an asp.net with asp.net AJAX.
My XML document is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<hotels>
<hotel supplier="Sarova panafric" id="HTL-10001">
<supplier>Sarova panafric</supplier>
<contact>Mr S Njoroge</contact>
<tel>75-525254</tel>
</hotel>
<hotel supplier="Sarova mara" id="HTL-10002">
<supplier>Sarova mara</supplier>
<contact>Mr ole seni</contact>
<tel>20-54574</tel>
</hotel>
</hotels>
This is the JavaScript function I use to try and insert data in my XML file:
function addhotels() {
var xml;
if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xml = new XMLHttpRequest();
}
xml.open("GET", "hotelRates.xml", true);
xml.send(null);
var hotel = xml.responseXML.createElement("hotel");
var supplier = xml.responseXML.createElement("supplier");
supplier.appendChild(xml.responseXML.createTextNode("Sarova stanley"));
var contact = xml.responseXML.createElement("contact");
contact.appendChild(xml.responseXML.createTextNode("Mr Njoroge"));
var tel = xml.responseXML.createElement("tel");
tel.appendChild(xml.responseXML.createTextNode("21454741"));
hotel.appendChild(supplier);
hotel.appendChild(contact);
hotel.appendChild(tel);
xml.responseXML.appendChild(hotel);
}
The XML file is sitting on the root folder of my project, where pages are located.
I don't know why it doesn't work.
============================== I have now changed the code as follows, but still no effect.
function addhotels() {
var xml;
if (window.ActiveXObject) {
xml = new ActiveXObject("Microsoft.XMLHTTP");
} else {
xml = new XMLHttpRequest();
}
xml.open("GET", "hotelRates.xml", true);
xml.send(null);
var hotels = xml.responseXML.createElement("hotels");
var supplier = xml.responseXML.createElement("supplier");
supplier.appendChild(xml.responseXML.createTextNode("Sarova stanley"));
var contact = xml.responseXML.createElement("contact");
contact.appendChild(xml.responseXML.createTextNode("Mr Njoroge"));
var tel = xml.responseXML.createElement("tel");
tel.appendChild(xml.responseXML.createTextNode("21454741"));
hotels.appendChild(supplier);
hotels.appendChild(contact);
hotels.appendChild(tel);
xml.responseXML.appendChild(hotels);
}
xml.responseXML.appendChild. You cannot append to the document itself, as mentioned in both answers below.