gpt4 book ai didi

javascript - 如何使用 JavaScript 从 XML 调用特定条目

转载 作者:行者123 更新时间:2023-11-29 23:05:32 25 4
gpt4 key购买 nike

所以我有这个 XML 代码

<book>
<bookname>book1</bookname>
<author>authorman</author>
</book>
<book>
<bookname>book2</bookname>
<author>authorperson</author>
</book>

我希望能够根据作者的姓名使用作者获取书名,反之亦然,并使用 JavaScript 将其分配给变量。我试图避免使用服务器端编程,只想使用 JavaScript。这是我第一次在这里发帖,因为我是一名最近学习编程的高中生。

最佳答案

可以设置XMLHttpRequest() responseType属性(property)"document" , overrideMimeType()设置为 "text/html"获取 HTML #document作为responseload 内处理程序。

创建一个函数,它期望一个普通对象作为参数传递,具有 "author""bookname"值设置为 textContent 的属性的 XML <book>元素 <bookname><author>匹配。迭代 NodeList<book>元素和 children HTMLCollection , 检查是否 localName等于"bookname""author" , 和 textContent匹配传递给函数的参数,如果为真,则获取 parentElement引用,使用.querySelector()"bookname"如果 "author" 通过是对象参数的属性,或 "author"如果"bookname"作为参数传递,返回textContent匹配元素,或 '"author of <bookname> OR book by <author>" not found.' .

const request = new XMLHttpRequest();
request.responseType = "document";
request.overrideMimeType("text/html");
const xml = `<?xml version="1.0" encoding="UTF-8"?><book>
<bookname>book1</bookname>
<author>authorman</author>
</book>
<book>
<bookname>book2</bookname>
<author>authorperson</author>
</book>`;
const getBookData = (books, {bookname, author} = {}) => {
for (const {children} of books) {
for (const book of children) {
const {localName, textContent} = book;
if (localName === "bookname" && bookname === textContent
|| localName === "author" && author === textContent) {
return book.parentElement
.querySelector(author ? "bookname" : "author")
.textContent
}
}
}
return `${author ? "book by" : "author of"} "${bookname || author}" not found in library.`;
}
request.addEventListener("load", e => {
const html = request.response;
const books = html.querySelectorAll("book");
console.log(getBookData(books, {author:"authorman"}));
console.log(getBookData(books, {bookname:"book2"}));
console.log(getBookData(books, {author:"authorx"}));
console.log(getBookData(books, {bookname:"book3"}));
})
request.open("GET", `data:application/xml,${encodeURIComponent(xml)}`);
request.send();

关于javascript - 如何使用 JavaScript 从 XML 调用特定条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54849674/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com