Reputation: 1597
suppose I have two strings with XML inside. Something like this:
<playlist>
<item id="1">
...
</item>
</playlist>
and
<playlist>
<item id="2">
...
</item>
</playlist>
What I want to obtain is this:
<playlist>
<item id="1">
...
</item>
<item id="2">
...
</item>
</playlist>
Then I do this:
oldPlaylist = $.parseXML(string1);
newPlaylist = $.parseXML(string2);
$(oldPlaylist).find('playlist').each(function(index,playlist) {
$(newPlaylist).find('item').each(function(index2,item) {
$(playlist).add(item);
});
});
answer = (new XMLSerializer()).serializeToString(oldPlaylist);
But it doesn't work. Answer is the same that string1. I can say that with the example supplied, this enters to the first each one time, and to the second each one time too (then seems that it reads correctly both XML).
What do you think? Can you help me? Thank you!
Upvotes: 2
Views: 154
Reputation: 27996
Looks to me like add()
is the wrong thing to use. It merely adds the item to the set of matched elements... it does not insert a new child element into a tree.
Instead, you want append()
. And append()
actually modifies the object it's operating on, so you don't need to assign the result to oldPlaylist
.
So I would try something like
var oldPlaylist = $.parseXML(string1);
var newPlaylist = $.parseXML(string2);
$(oldPlaylist).find('playlist').each(function(index, playlist) {
$(newPlaylist).find('item').each(function(index2, item) {
$(playlist).append(item);
});
});
answer = (new XMLSerializer()).serializeToString(oldPlaylist);
I tested this and it gives the desired answer
:
<playlist>
<item id="1"> ... </item>
<item id="2"> ... </item>
</playlist>
(Indentation added for clarity.)
Upvotes: 2
Reputation: 8372
According to the documentation, the add method constructs a new jQuery object and returns it. It doesn't actually change the object on which you call the method.
So it's normal that the answer is the same string as string1.
You could do something along these lines:
var oldPlaylist = $.parseXML(string1);
var newPlaylist = $.parseXML(string2);
$(newPlaylist).find('item').each(function(index,item) {
oldPlaylist = oldPlaylist.add(item);
});
answer = (new XMLSerializer()).serializeToString(oldPlaylist);
Upvotes: 4