2

So i have this XML code

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

and I want to be able to get the bookname using the author according to the author's name or vice versa and assign it to variable using JavaScript. I am trying to avoid using server-side programming and want to use JavaScript only. This is my first time posting here since I am a high school student that recently learned to program.

3 Answers 3

1

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();

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This worked like a charm but now i want to expand my search methods, what I need to do is the xml code
0

try this

  var text, parser, xmlDoc;  

    text="<book>
    <bookname>book1</bookname>
    <author>authorman</author>
    </book>
    <book>
    <bookname>book2</bookname>
    <author>authorperson</author>
    </book>";  

    parser = new DOMParser();
    xmlDoc = parser.parseFromString(text,"text/xml");

    console.log(xmlDoc.getElementsByTagName("book")[0].childNodes[0].nodeValue); //book1

    console.log(xmlDoc.getElementsByTagName("book")[1].childNodes[0].nodeValue); //book2

Comments

0

Hope this will help you :-

<script type="text/javascript">
  var xml = "<xml>"+
            "<book>"+
              "<bookname>book1</bookname>"+
              "<author>authorman</author>"+
            "</book>"+
            "<book>"+
              "<bookname>book2</bookname>"+
              "<author>author2</author>"+
            "</book>"+
            "</xml>";

  parser = new DOMParser();
  xmlDoc = parser.parseFromString(xml,"text/xml");
  authors   = xmlDoc.getElementsByTagName("author");
  booknames = xmlDoc.getElementsByTagName("bookname");

  var bookname = searchByAuthor('authorman', authors, booknames);
  alert(bookname);

  var authorname = searchByBookName('book2', authors, booknames);
  alert(authorname);
  
  function searchByAuthor(author_name, x, y){
      
      for (i = 0; i < x.length; i++) {
          if(x[i].childNodes[0].nodeValue == author_name){
            return y[i].childNodes[0].nodeValue;
          }  
      }
  }

  function searchByBookName(book_name, x, y){

    for (i = 0; i < y.length; i++) {
          if(y[i].childNodes[0].nodeValue == book_name){
            return x[i].childNodes[0].nodeValue;
          }  
      }
  }
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.