I am writing a Firefox extension. Right now I need to create a local copy of a XML file and I am almost successful. A File is read and a new one is created but this one is empty. Is there a special method for XML files or why does it not work?
Here are the functions:
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;
}
and
function localcopy() {
var url = content.document.location.href;
var prefManagerr = Components.classes["@mozilla.org/preferences-service;1"]
.getService(Components.interfaces.nsIPrefService)
.getBranch("extensions.foafnet.");
var prefStringx;
if (prefManagerr.prefHasUserValue("stringpref1")) {
prefStringx = prefManagerr.getCharPref("stringpref1");
} else {
// Preference is default value so use that
prefStringx = "0"
}
if (prefStringx == url) {
xml = loadXMLDoc(prefStringx);
var file = Components.classes["@mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("TmpD", Components.interfaces.nsIFile);
file.append("profiletemp.xml");
file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0666);
// do whatever you need to the created file
alert(file.path);
//
var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"].
createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(file, 0x04 | 0x08 | 0x20, 0600, 0); // readwrite, create, truncate
stream.write(xml, xml.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
}
}
The beginning of the second function just declares, that a local copy is only to be made if the called website hast the same url as a url defined in the preferences of the extension. this part works just fine.
The first parameter to
nsIOutputStream.write()has to be a string – you are giving it an XML document instead. You can use XMLSerializer to convert XML into text and to write it to a stream directly: