XML 存入 localStorage 必须用 encodeURIComponent 编码,读取时 decodeURIComponent 解码;需校验长度防超限、检查格式合法性,并用 DOMParser 解析后验证 parsererror;不推荐字符串拼接构造 XML,大 XML 应改用 IndexedDB。
localStorage
localStorage 只接受字符串,而 XML 常含 、>、& 等非法字符,直接调用 setItem('xml', xmlString) 会静默失败或截断数据。
getItem() 可能返回 null 或不完整字符串encodeURIComponent() 编码后存储,读取时用 decodeURIComponent() 解码JSON.stringify() 包一层——它不解决 XML 特殊字符问题,反而多套一层引号和转义localStorage 容量限制更严,XML 易超限多数现代浏览器允许 localStorage 达 5–10MB,但 IE11 实际可用常低于 2.5MB,且对单个 key 的写入有隐式长度限制(约 1.5MB 左右)。
QuotaExceededError
if (xmlString.length > 1000000) { /* 考虑分片或改用 IndexedDB */ }try {
localStorage.setItem('xml', encoded);
} catch (e) {
if (e.name === 'QuotaExceededError') { /* 处理容量不足 */ }
}从 localStorage 读出的 XML 字符串可能因编码/截断/意外修改而损坏,直接丢给 DOMParser 会抛 SyntaxError。
const raw = localStorage.getItem('xml');
const decoded = decodeURIComponent(raw || '');
if (!decoded.trim().startsWith('
console.error('XML 格式异常:开头缺失');
}DOMParser 解析时务必检查 parseFromString 返回的文档是否有 parsererror 元素doc.documentElement,防止 undefined 报错localStorage 是纯字符串容器,不理解 XML 结构。所有语义(如 、xmlns 属性、处理指令)都原样保存,但容易因手动拼接或编辑被破坏。
XMLSerializer 序列化真实 DOM 文档,而非手写字符串encodeURIComponent 后仍可安全 round-trip,但人工编辑 JSON-like 字符串时极可能误删 ]]>
XML 不是为键值存储设计的格式,localStorage 存 XML 的本质是“把结构化数据降级为字符串”,所有解析、校验、容错都要自己补全。稍大一点的 XML,真该直接切到 IndexedDB。