Skofo
Skofo

Reputation: 143

Editing an XML file with JavaScript?

Is it possible to get an XML file (not HTML) from a server, add/remove/edit particular parts of it with client-side JavaScript, and then send it back to the server to save it? JSON or any other markup/data interchange format works too.

Upvotes: 3

Views: 5961

Answers (5)

John Kugelman
John Kugelman

Reputation: 361547

Sure. You can use an XMLHttpRequest to fetch an XML document if the server serves it using the text/xml MIME type. The responseText property will give you the XML text, but the browser will also parse the XML for you and provide a DOM tree in responseXML. You can modify that DOM as you please and then serialize it and send it back to the server.

You can also use JSON the same way. You use XMLHttpRequest to get the data from the server, then jsonData = eval(xhr.responseText) to get turn the JSON data into JavaScript objects.

Every major JavaScript library has modules/functions to aid doing either of these methods. XML and JSON are the two most popular data exchange methods in Ajax applications.

Upvotes: 0

Josh Stodola
Josh Stodola

Reputation: 82483

Yes. Using jQuery...

$.get("myGetUrl.php", function(data) {
  var xml = $(data);

  xml.find("myNode").text("newValue");

  $.post("myPostUrl.php", xml, function(resp) {
    alert(resp);
  }, "xml");
});

Upvotes: 3

defines
defines

Reputation: 10524

Certainly. You can use the XMLHttpRequest object to make the request for the file, do any operations you need to the data, and then post the entire document back using another XMLHttpRequest. You could do this with XML (and that is probably easiest for downloading the original document), but you would probably have the easiest time using JSON for the post back to the server.

You will need a server-side script (i.e. PHP, ASP, Ruby) to receive the posted data, format it however desired (i.e. turn the JSON into an XML document) and save it either as a file or in a database.

This question is far too general to get into specific implementation yet, but if you need additional help with these steps just ask.

Upvotes: 0

Alan Plum
Alan Plum

Reputation: 10892

Yes. You can read an XML document via AJAX and traverse its DOM like you would with HTML. If you use a framework like jQuery, it's even easier.

Upvotes: 0

Paulo Santos
Paulo Santos

Reputation: 11567

Yes it's possible. Seach for "XML DOM", and you can edit it on the client quite easily.

Upvotes: 0

Related Questions