【发布时间】:2020-09-28 12:01:44
【问题描述】:
我有一个 JS 代码,它创建一个 XML 并在本地存储上解析它。问题是我无法将更多 XML 附加到本地存储中。下面的例子。
<?xml version="1.0" encoding="UTF-8"?>
<club>
<movie>
<title> I Love Programming </title>
<genre> Action </genre>
<dir> Brian De Palma </dir>
<year> 1900 </year>
</movie>
</club>
我将上面的代码保存到本地存储中,但如果我想保存更多相同的 XML,它会创建另一个 XML 文件,插入 将其推送到现有文件。
function addXMLtoLocalStorage(e){
txt1 = `<?xml version="1.0" encoding="UTF-8"?>`
txt2 = `<club>`
txt3 = `<movie>`
txt4 = `<title>` + userInput[0] + `</title>`
txt5 = `<genre>` + userInput[1] + `</genre>`
txt6 = `<dir>` + userInput[2] + `</dir>`
txt7 = `<year>` + userInput[3] + `</year>`
txt8 = `</movie>`
txt9 = `</club>`
txt=txt1+txt2+txt3+txt4+txt5+txt6+txt7+txt8+txt9;
console.log(txt);
parser = new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
console.log(xmlDoc);
localStorage.setItem('data', xmlDoc);
}
如何在每次运行函数时将新生成的 XML 附加到第一个 XML 文件中,以便每次都创建一个新的?
预期输出
<?xml version="1.0" encoding="UTF-8"?>
<club>
<movie>
<title> I Love Programming </title>
<genre> Action </genre>
<dir> Brian De Palma </dir>
<year> 1900 </year>
</movie>
</club>
<!--Now add the following info below, not creating a new XML file.-->
<club>
<movie>
<title> I Love Programming The Sequel </title>
<genre> Action </genre>
<dir> Brian De Palma </dir>
<year> 1920 </year>
</movie>
</club>
<!-- Every new Club instance is when the function above is runned -->
<club>
<movie>
<title> Help! Me </title>
<genre> Thriller </genre>
<dir> Spielberg </dir>
<year> 2020 </year>
</movie>
</club>
【问题讨论】:
-
先获取旧的(存储的)一个,然后用新的 xml 更新旧的。获取项目存储在使用 localStorage
localStorage.getItem('data'); -
@SameerKhan 谢谢,如果你介意的话,你能解释一下如何发展你所说的吗?谢谢!
-
请注意,localStorage 只存储 string 值。因此,在将 XML 存储到 localStorage 之前对其进行解析是徒劳的。您应该将字符串存储在 localStorage 中,并在离开 localStorage 时对其进行解析。
-
userInput来自哪里? -
@HereticMonkey 来自表单
标签: javascript html xml parsing dom