我是一个REST端点,它返回这样的XML(当然,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>
&#13;
现在我想基于某个标记值动态过滤它,只保留tag = value的块(然后将其转换为对象)。 对于这个例子,我想只保留genre = Fantasy的书籍,并将字段价格,标题和作者投射到我的BookInfo对象。我想避免创建一个xml解析器。我可以用JOOX做吗?
答案 0 :(得分:1)
jOOX允许对这些用例使用两种类型的查询语言:
由于jOOX的灵感来自jQuery,因此CSS选择器可通过Match.find()
方法获得。它们对于非常简单的查询很有用。在内部,它们被翻译为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()
));