Reputation: 863
I am getting error on document.adoptNode
as 'parameter1 is not valid node'.
Below is my code.
$.ajax({
type: "GET",
url: url,
datatype: "xml",
success: function (results) {
//results is a XMLDocument type object which contains a SVG information
console.log(results);
//need to serialize results to store it in localStorage
localStorage.setItem('results', JSON.stringify(results));
var results2 = JSON.parse(localStorage.getItem('results'));
var svgnode = $('svg', results);
var origwidth = svgnode.attr('width');
var origheight = svgnode.attr('height');
var docnode = document.adoptNode(svgnode[0]);
}
});
I need serialization and deserialization to store it in localStorage. How can i serialize and deserialize XMLDocument?
Upvotes: 1
Views: 1701
Reputation: 1074585
XML has its own text format, I wouldn't use JSON for the serialization/deserialization, I'd use XML.
In your ajax call, you're asking jQuery to deserialize the XML text received for you. But since you want to use that text, I'd change dataType
to "text"
so you receive a string with the XML in it. Then store that in localStorage
and parse it when you need an XMLDocument
instead of a string.
Something along these lines:
$.ajax({
type: "GET",
url: url,
datatype: "text",
success: function(results) {
// `results` is a string
localStorage.setItem('results', results);
// No need to re-get it, you already have it in `results`; parse it
var results2 = new DOMParser().parseFromString(results, "text/xml");
var svgnode = $('svg', results);
var origwidth = svgnode.attr('width');
var origheight = svgnode.attr('height');
var docnode = document.adoptNode(svgnode[0]);
}
});
Or you can parse it with jQuery instead:
$.ajax({
type: "GET",
url: url,
datatype: "text",
success: function(results) {
// `results` is a string
localStorage.setItem('results', results);
// No need to re-get it, you already have it in `results`; parse it
var svgnode = $.parseXML(results);
var origwidth = svgnode.attr('width');
var origheight = svgnode.attr('height');
var docnode = document.adoptNode(svgnode[0]);
}
});
If you ever need to go from an XMLDocument
to a string again, you can do that like this:
var xmlString = new XMLSerializer().serializeToString(xmlDocument);
Upvotes: 2