1

I've a REST endpoint that returns XML like this (the XML is of course bigger say around 10,000 blocks of data vs the 3 blocks I show in this example):

<?xml version="1.0"?>
<catalog>
  <book id="bk101">
    <author>Gambardella, Matthew</author>
    <title>XML Developer's Guide</title>
    <genre>Computer</genre>
    <price>44.95</price>
    <publish_date>2000-10-01</publish_date>
    <description>An in-depth look at creating applications with XML.</description>
  </book>
  <book id="bk102">
    <author>Ralls, Kim</author>
    <title>Midnight Rain</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-12-16</publish_date>
    <description>A former architect battles corporate zombies,       an evil sorceress, and her own childhood to become queen       of the world.</description>
  </book>
  <book id="bk103">
    <author>Corets, Eva</author>
    <title>Maeve Ascendant</title>
    <genre>Fantasy</genre>
    <price>5.95</price>
    <publish_date>2000-11-17</publish_date>
    <description>After the collapse of a nanotechnology       society in England, the young survivors lay the       foundation for a new society.</description>
  </book>
</catalog>

Now I want to filter it on the fly based on certain tag value and just retain the blocks where tag=value (and then cast it into an object). For this example I'd like to keep only the books where genre=Fantasy and just cast the fields price, title and author to my BookInfo object. I want to avoid creating a xml parser. Can I do it with JOOX ?

Morgoth
  • 4,935
  • 8
  • 40
  • 66
Yana
  • 293
  • 1
  • 3
  • 11
  • Yes, you can. This is a basic use-case for JOOX. See projects github page for all the details you need: https://github.com/jOOQ/jOOX. If it does not work for you, come back here and explain what you tried and what does not work. – rmuller Mar 20 '17 at 12:41

1 Answers1

1

jOOX allows for using two types of query languages for these kinds of use-cases:

CSS Selectors

Because jOOX is inspired by jQuery, CSS selectors are available through the Match.find() method. They're useful for very simple queries. Internally, they're translated to XPath, which is the second query language:

XPath

XPath is the ideal query language for searching content in XML documents. You can use the Match.xpath() method to search for fantasy books, for instance:

Match match = $(xml).xpath("/catalog/book[genre=\"Fantasy\"]");

From there on, you can further process your books, e.g. printing them:

$(xml).xpath("/catalog/book[genre=\"Fantasy\"]")
      .each(System.out::println);

Or mapping them into your BookInfo type:

List<BookInfo> books = 
$(xml).xpath("/catalog/book[genre=\"Fantasy\"]")
      .map(book -> new BookInfo(
          $(book).child("price").text(BigDecimal.class),
          $(book).child("title").text(),
          $(book).child("author").text()
      ));
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509