我现在有一个问题:我有一个js代码,可以创建一个XML文档,一个简单的。问题是,当我重新运行创建文档的函数时,它将旧的替换为新的。
我想做这样的事情。
<root>
<person>
<name>Jon</name>
<age>18</age>
</person>
<person>
<name>Paco</name>
<age>76</age>
</person>
<person>
<name>Marta</name>
<age>42</age>
</person>
</root>
但我一次只能处理一个文档, 我不能把新创建的xml文档 "追加或推送 "到第一个文档里. 本地存储总是存储最新的.我的JS代码
用户输入来自表单标签
function addTodo(e) {
e.preventDefault();
const userInputHTMLCollection = document.getElementsByClassName("userAdd");
console.log(userInputHTMLCollection);
// EDITOR: added missing '=' below:
const userInput = [].map.call(
userInputHTMLCollection,
(element) => element.value
);
console.log(userInput[0]);
console.log(userInput[1]);
console.log(userInput[2]);
console.log(userInput[3]);
//Creem la plantilla XML.
txt1 = `<?xml version="1.0" encoding="UTF-8"?>`;
txt2 = `<filmoteca>`;
txt3 = `<peli>`;
txt4 = `<titol>` + userInput[0] + `</titol>`;
txt5 = `<genere>` + userInput[1] + `</genere>`;
txt6 = `<director>` + userInput[2] + `</director>`;
txt7 = `<any>` + userInput[3] + `</any>`;
txt8 = `</peli>`;
txt9 = `</filmoteca>`;
txt = txt1 + txt2 + txt3 + txt4 + txt5 + txt6 + txt7 + txt8 + txt9;
console.log("Text Principal" + txt);
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt, "text/xml");
localStorage.setItem("data", xmlDoc);
console.log(xmlDoc);
var xmlString = new XMLSerializer().serializeToString(xmlDoc);
console.log(xmlString);
// ...
}
下面的函数将创建一个XMLDocument到LocalStorage中,但我想继续添加更多的XML。
以下是试图将新的xml添加或推送到旧的xml中的代码。
function afegirLS() {
const userInputHTMLCollection = document.getElementsByClassName("userAdd");
const userInput = [].map.call(
userInputHTMLCollection,
(element) => element.value
);
var informacio = localStorage.getItem("data");
txt2 = `<filmoteca>`;
txt3 = `<peli>`;
txt4 = `<titol>` + userInput[0] + `</titol>`;
txt5 = `<genere>` + userInput[1] + `</genere>`;
txt6 = `<director>` + userInput[2] + `</director>`;
txt7 = `<any>` + userInput[3] + `</any>`;
txt8 = `</peli>`;
txt9 = `</filmoteca>`;
txt_nou = txt1 + txt2 + txt3 + txt4 + txt5 + txt6 + txt7 + txt8 + txt9;
console.log("Text Nou" + txt_nou);
parser2 = new DOMParser();
afegirXML = parser2.parseFromString(txt_nou, "text/xml");
console.log(afegirXML);
//var xmlString2 = new XMLSerializer().serializeToString(string_vell);
//console.log(xmlString2);
//txt_nou.push(xmlString);
}
似乎你想将多个XML文档存储到localStorage中,但你只存储了一个文档。
function addTodo(e) {
// ...
xmlDoc = parser.parseFromString(txt, "text/xml");
localStorage.setItem("data", xmlDoc);
// ...
}
如果你想存储多个文档,你可以存储和检索一个数组。
let xmlDocs = [];
/ ...
function addTodo(e) {
let xmlDocs = JSON.parse(localStorage.getItem('data')) || [];
// ...
xmlDoc = parser.parseFromString(txt, "text/xml");
xmlDocs.push(xmlDoc);
localStorage.setItem('data', JSON.stringify(xmlDocs));
// ...
}
注意使用 JSON.stringify()
将数组转换为字符串,而 JSON.parse()
来将字符串转换回数组。这保证了 localStorage
只存储字符串(根据需要)。