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?
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?
Share Improve this question asked Mar 25, 2014 at 22:28 Thijs KoerselmanThijs Koerselman 23.3k25 gold badges84 silver badges119 bronze badges4 Answers
Reset to default 6To 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()
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
You dont need jquery to this, use XMLSerializer
new XMLSerializer().serializeToString(xmlobj.documentElement);
As long as your XML document does not contain some extra fancy namespaces, then it's simple:
var newxmlstring = $xml.html();