1

我有一个像这样返回 XML 的 REST 端点(XML 当然更大,比如大约 10,000 个数据块,而我在本示例中显示的 3 个块):

<?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>

现在我想根据某些标签值动态过滤它,并只保留 tag=value 的块(然后将其转换为对象)。对于这个例子,我想只保留genre=Fantasy 的书籍,并将字段价格、标题和作者转换为我的BookInfo 对象。我想避免创建 xml 解析器。我可以用 JOOX 做吗?

4

1 回答 1

1

jOOX 允许对这些用例使用两种类型的查询语言:

CSS 选择器

因为 jOOX 受到jQuery的启发,所以可以通过该Match.find()方法使用 CSS 选择器。它们对于非常简单的查询很有用。在内部,它们被翻译成 XPath,这是第二种查询语言:

XPath

XPath 是用于在 XML 文档中搜索内容的理想查询语言。您可以使用该Match.xpath()方法搜索奇幻书籍,例如:

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

从那里开始,您可以进一步处理您的书籍,例如打印它们:

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

或者将它们映射到您的BookInfo类型中:

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()
      ));
于 2017-03-20T15:35:20.437 回答