HTML5 sessionStorage 和 XMLDocument

发布于 2025-01-05 15:16:31 字数 282 浏览 1 评论 0原文

我想在 sessionStorage 中存储 XML 文档。当我这样做时,它似乎可以保存为 XMLDocument。当我尝试访问它(在页面刷新时)时,该对象以 [object Object] 形式返回,而不是 [object XMLDocument]

如何以 XMLDocument 的形式从 sessionStorage 中获取数据(或将其转换为 XMLDocument?)

I want to store an XML document in sessionStorage. When I do this it seems to save ok as an XMLDocument. When I try to access it (on a page refresh) the object comes back as [object Object] as opposed to [object XMLDocument].

How do I get the data out of sessionStorage as an XMLDocument (or convert it to one?)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

您可能希望在将 XMLDocument 保存到存储之前对其进行序列化:

var xml = new XMLSerializer().serializeToString(originalDom);
sessionStorage.setItem("myDocument", xml);

然后在从存储加载数据后进行反序列化:

var xml = sessionStorage.getItem("myDocument");
var restoredDom = new DOMParser().parseFromString(xml, "text/xml");

You may want to serialize XMLDocument before saving it in storage:

var xml = new XMLSerializer().serializeToString(originalDom);
sessionStorage.setItem("myDocument", xml);

and then unserialize after loading data from storage:

var xml = sessionStorage.getItem("myDocument");
var restoredDom = new DOMParser().parseFromString(xml, "text/xml");
殊姿 2025-01-12 15:16:31

localStoragesessionStorage 只能保存字符串。查看接口定义

interface Storage {
  readonly attribute unsigned long length;
  [IndexGetter] DOMString key(in unsigned long index);
  [NameGetter] DOMString getItem(in DOMString key);
  [NameSetter] void setItem(in DOMString key, in DOMString data);
  [NameDeleter] void removeItem(in DOMString key);
  void clear();
};

除非序列化对象,否则无法存储对象。因此,就您而言,您必须 将其序列化为 XML

如果您收到的是文本形式的 XML 文档,则直接存储它即可。您可以使用 jQuery.parseXML() 来解析它检索。

localStorage and sessionStorage can only hold strings. Have a look at the interface definition:

interface Storage {
  readonly attribute unsigned long length;
  [IndexGetter] DOMString key(in unsigned long index);
  [NameGetter] DOMString getItem(in DOMString key);
  [NameSetter] void setItem(in DOMString key, in DOMString data);
  [NameDeleter] void removeItem(in DOMString key);
  void clear();
};

You cannot store objects unless you serialize them. So in your case, you have to serialize it to XML.

If you received the XML document as text, just store it directly. You can use jQuery.parseXML() to parse it after retrieval.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文