You can set XMLHttpRequest() responseType property to "document", overrideMimeType() set to "text/html" to get an HTML #document as response within load handler.
Create a function which expects a plain object to be passed as parameter, having either "author" or "bookname" property with value set to the textContent of the XML <book> element <bookname> or <author> to match. Iterate the NodeList of <book> elements and children HTMLCollection, check if localName is equal to "bookname" or "author", and the textContent matches parameter passed to function, if true, get parentElement reference, use .querySelector() with either "bookname" passed if "author" is property of object parameter, or "author" if "bookname" is passed as parameter, return textContent of matched element, or '"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();