Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert xml document back to string with jQuery

I am trying to parse an xml formatted string, remove one of its elements, and write it back to a string. All with standard jQuery functions. It's the last step that I can't seem to figure out.

var $xml = $(somexmlstring);
var element = $xml.find('name:contains("'+somevalue+'")');
element.remove();
var newxmlstring = $xml.dunno(); 

What function can I use to convert the $xml DOM back to a string?

like image 637
Thijs Koerselman Avatar asked Mar 25 '14 22:03

Thijs Koerselman


2 Answers

To help you fix your code in the jsfiddle:

var data = '<value><url>foo</url><name>bar</name></value><value><url>foo</url><name>bar</name></value>'
var xml = $.parseXML('<root>' + data + '</root>');
var $xml = $(xml);
console.log('xml', $xml.find('root').html());

The fix is in the last line: `$xml.find('root').html()

like image 168
RemyNL Avatar answered Sep 22 '22 12:09

RemyNL


You can use .html() if you wrap the jQuery object with a parent element first and then call .html() on the parent element.

var $xml = $(somexmlstring);
$xml.find('name:contains("' + somevalue + '")').remove();
var newxmlstring = $('<x></x>').append($xml).html(); 

This works even if the original XML string does not have a single root element. It does not work, however, if the original XML string contains an XML declaration (like <?xml version="1.0" encoding="UTF-8"?>).

jsfiddle


If the original XML string is a valid XML document, optionally containing an XML declaration at the beginning, you may want to create the jQuery object like this:

var $xml = $($.parseXML(somexmlstring).documentElement);
$xml.find('name:contains("' + somevalue + '")').remove();
var newxmlstring = $('<x></x>').append($xml).html(); 

jsfiddle

like image 37
John S Avatar answered Sep 20 '22 12:09

John S