skip to Main Content

In below example I want to find the values of author, year & price using the value ‘Harry potter’ as my input in jquery

<bookstore>
     <book>
      <title>Everyday Italian</title>
      <author>Giada De Laurentiis</author>
      <year>2005</year>
      <price>30.00</price>
     </book>
     <book>
      <title>Harry Potter</title>
      <author>J K. Rowling</author>
      <year>2005</year>
      <price>29.99</price>
     </book>
    </bookstore>

2

Answers


  1. Use Powershell

    using assembly System.Xml.Linq
    
    $filename = "c:temptest.xml"
    
    $doc = [System.Xml.Linq.XDocument]::Load($filename)
    $books = $doc.Descendants("book")
    
    $table = [System.Collections.ArrayList]::new()
    foreach($book in $books)
    {
       $title = $book.Element('title').Value
       $author = $book.Element('author').Value
       $year = $book.Element('year').Value
       $price = $book.Element('price').Value
       $newRow = [pscustomobject]@{
          title=$title
          author=$author
          year=$year
          price=$price
       }
       $table.Add($newRow) | Out-Null
    }
    $table | Format-Table
    

    Results

    title            author              year price
    -----            ------              ---- -----
    Everyday Italian Giada De Laurentiis 2005 30.00
    Harry Potter     J K. Rowling        2005 29.99
    
    Login or Signup to reply.
  2. There is many ways you can attack it. Easist way is to use jQuery to convert it to XML (if you did not have it in that format already). You can then loop over it and find the titles and filter on those that match the same text. After that you can get the book and loop over the children to get the properties you are after.

    const xmlString = `
    <bookstore>
      <book>
        <title>Everyday Italian</title>
        <author>Giada De Laurentiis</author>
        <year>2005</year>
        <price>30.00</price>
      </book>
      <book>
        <title>Harry Potter</title>
        <author>J K. Rowling</author>
        <year>2005</year>
        <price>29.99</price>
      </book>
    </bookstore>
    `;
    
    // convert the xml into an object
    const doc = $($.parseXML(xmlString));
    
    // find all the titles that match
    const titles = doc.find('book title').filter((_, title) => title.textContent === 'Harry Potter');
    
    const data = titles.get().map((title) => {
      const book = $(title).parent();
      return book.children().get().reduce((obj, elem) => ({...obj, [elem.tagName]: elem.textContent}), {});
    });
    
    console.log(data);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search