Как извлечь строку в xml с помощью Gpath

Доброе утро!
Юзаю библиотеку rest-assured. Она депендит себе XmlPath для обработки xml доков по средством Gpath выражений.

Вот хочу вычленить строку из вложенного элемента по тексту родительского элемента.



String xml = "<shopping>\n" +
                "      <category type=\"groceries\">\n" +
                "        <staff>Chocolate<price>10</price></staff>\n" +
                "        <staff>Coffee<price>15</price></staff>\n" +
                "      </category>\n" +
                "      <category type=\"supplies\">\n" +
                "        <staff>Paper</staff>\n" +
                "        <staff quantity=\"4\">Pens</staff>\n" +
                "      </category>\n" +
                "      <category type=\"present\">\n" +
                "        <staff when=\"Aug 10\">Kathryn's Birthday</staff>\n" +
                "      </category>\n" +
                "</shopping>";



XmlPath xmlPath = new XmlPath(xml);

String price = 
xmlPath.getString("shopping.category.staff.find{it.text()=='Chocolate'}.price"));

Не находит price… просто выдает пустую строку.
Может знаете туториал по Gpath, я правда не нашел.

Привет.

Под рукой есть только груви консоль, поэтому ответ по GPath

def shopping = new XmlSlurper().parseText(xml)
def price = shopping.'*'.staff.find{ it.toString().contains('Chocolate') }.price

В твоем xml нельзя так сравнивать

it.text()=='Chocolate'

потому что нода staff содержит внутри себя price

def price = shopping.'*'.staff.find{println it }
//Chocolate10

2 лайка

THNKS!
YOU SAVED MY DAY!

В джаве выглядит так:


XmlPath xmlPath = new XmlPath(xml);
String price = xmlPath.getString("shopping.category.staff.find{ it.toString().contains('Chocolate') }.price");

Привет :slight_smile:
Можно немного упростить it.toString().contains('Chocolate'), заменив его на it=~'Chocolate' :slight_smile:
В итоге получим: xmlPath.getString("shopping.category.staff.find{ it=~'Chocolate' }.price");

2 лайка

Премного благодарен!
Вообще Gpath очень интересно! Правда я некоторые вещи из Xpath не могу спроецировать на Gpath, ибо там законы немного другие, right?

Возможно)) Я не работала с GPath (в “чистом его виде”) :slight_smile:
Пока только с JsonPath (rest-assured) и Jayway’s JsonPath)

1 лайк

Немного дургие.

GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be 
identified. In this sense, it has similar aims and scope as XPath does for XML. GPath is often used in the context of 
processing XML, but it really applies to any object graph. Where XPath uses a filesystem-like path notation, a tree 
hierarchy with parts separated by a slash /, GPath use a dot-object notation to perform object navigation.

Задавай вопросы, кто то да поможет.

Про Gpath можно почитать более подробно тут

1 лайк