首页 > 解决方案 > 使用 grep 在 XmlPath 表达式中查找部分字符串匹配

问题描述

我正在使用 RestAssured 来帮助我进行一些测试。

给定以下 XML:

 <OptionalExtra ID="PREB" Description="Premium meal beef" Code="PREB" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="79.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
    <OptionalExtra ID="CHML" Description="Child meal" Code="CHML" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
    <OptionalExtra ID="VLML" Description="Vegetarian meal" Code="VLML" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
    <OptionalExtra ID="GFML" Description="Gluten-free meal" Code="GFML" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>

如何挑选出描述属性中包含“儿童”一词的所有餐食?我需要它不区分大小写。

以下不引发异常,但也找不到我需要的代码属性“CHML”:

List<String> allChildMeals;
            allChildMeals = response.xmlPath().getList("FAB_BasketRS.CurrentBasket.Itinerary.ItineraryOptions.OptionalExtra.findAll{it.@Type=='Meal' && it.@Description.grep(/[Child]/)}*.@Code");

我猜我的正则表达式/grep 是错误的?

标签: regexxpathrest-assuredgpath

解决方案


我已经设法使用这个 XPath 查询获得了您的 XML 的结果:

/foo/OptionalExtra[@Type='Meal' and contains(@Description, 'Child')]/@Code

我稍微修改了输入 - 将“foo”作为根节点插入并添加了第二个结果。

修改后的输入 XML:

<foo>
<OptionalExtra ID="PREB" Description="Premium meal beef" Code="PREB" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="79.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
        <OptionalExtra ID="CHML" Description="Child meal" Code="FIRST RESULT" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
        <OptionalExtra ID="VLML" Description="Vegetarian meal" Code="VLML" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
        <OptionalExtra ID="GFML" Description="Gluten-free meal" Code="GFML" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
        <OptionalExtra ID="CHML" Description="Child meal" Code="SECOND RESULT" Supplier="PRI" FPC="extra.pax.flightmeal" Type="Meal" QuantityAvailable="3" UnitCost="23.98" CurrencyCode="GBP" ApplyTo="SelectedPax"/>
</foo>

这是它的样子。这里使用的返回类型是“Nodeset”,否则不会返回所有结果。

在此处输入图像描述

您可以在 http://www.utilities-online.info/xpath/?save=55e705ac-14be-4d75-8fda-507c8da69e2d-xpath进行测试


推荐阅读