I want to delete some nodes or add some nodes in xml with jquery,
I try it with append
, empty
, remove
but all of them seem to not work,
like (in $.ajax):
success:function(xml){
$(xml).find("layout").append('<app id="' + $children.eq(i).attr("id") + '"></app>');
$(xml).find("layout").empty();
}
also I find there is no tutorial on google. So I wonder is it possible add or delete nodes in xml with jquery?
OK ,I write it in details,the xml file just save in local domain as Database/UserConfig/config.xml here is my Ajax code:
function layout_change()
{
var $children=$input.children();
$.ajax({
type: "get",
url: "Database/UserConfig/config.xml",
dataType: "xml",
timeout: 2000,
beforesend:function(xml){
$(xml).find("layout").empty();
},
success:function(xml){
for(var i=0;i<$children.length;i++)
{
$(xml).find("layout").append('<app id="' + $children.eq(i).attr("id") + '"></app>');
}
},
error:function(){}
});
}
or it can be done with javascript?or can be only done with server language like C#?……
here is my demo xml:
<layout>
<app id="id-4"></app>
<app id="id-5"></app>
<app id="id-6"></app>
<app id="id-1"></app>
<app id="id-2"></app>
<app id="id-3"></app>
</layout>
jQuery is a fantastic tool for parsing and manipulating XML in javascript. jQuery's ajax APIs were, in fact, built with this in mind which is why you're able to specify the response type of an ajax call by setting the
dataType
argument toxml
(although they do try to do some auto-detection if this argument is omitted). From the jQuery$.ajax()
documentation for thedataType
argument:You can parse and manipulate XML as much as want using jQuery. I'll have to add that using CSS selectors is wonderful compared to XPath queries in server-side XML libraries.
While
empty
andremove
work as expected, there's a gotcha when adding nodes on the fly with functions likeappend
: jQuery, for whatever reason (I haven't really dug into this), won't create the element for you when appending to the XML structure (although this works fine in HTML structures). You can get around this easily by explicitly creating the node yourself as a DOM element or jQuery object and then callingappend
:It looks like, however, that there are other problems with your code that would be preventing it from behaving as expected. The
$.ajax
beforeSend
callback, for example, passes in theXMLHttpRequest
object to the callback function and not your XML object to be manipulated. The result is that yourempty
call in that callback does nothing.Also, if you're trying to manipulate the response of
Database/UserConfig/config.xml
in thebeforeSend
callback, it probably won't have existed yet sincebeforeSend
is called before the ajax request is fired off. It's possible that thexml
argument you intended to pass in was scoped globally, but it's squashed in the scope of the callback since jQuery is passing inXMLHttpRequest
as I mentioned before.