简体   繁体   中英

Read and edit local xml-file in Javascript

I have a directory that contains

--index.html
--script.js
--file.xml

and I want to read the content of the file.xml as a string in order to replace a few words within the xml-file. (Later on I would like to send the edited xml-file as e-mail).

I managed to access to xml-file, but did not manage to save the whole content in a string and/or replace some known keywords within the xml.

This is where I got so far:

var oXHR = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');

function reportStatus2() {
  if (oXHR.readyState == 4)               // REQUEST COMPLETED.
     console.log(this.responseXML)        // This gets me the XML-document, but I want the complete xml content as string
}
oXHR.onreadystatechange = reportStatus2;    
oXHR.open("GET", "../file.xml", true);
oXHR.send();

I found so many posts on that topic here, but none was able to answer my question? Any ideas?

Look at thedocumentation for XMLHttpRequest .

Here is the documentation for the property you are reading:

XMLHttpRequest.responseXML Read only

Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML. Not available in workers.

Now look around. Just three entries earlier it says:

XMLHttpRequest.responseText Read only

Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.

So use that instead.


That said, XML is a structured data format with some fairly complex rules and it you should use DOM to edit it and not string manipulation (which is error prone and much more likely to result in invalid XML in your output).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM