Post

Check XML and HTML Responses in REST Assured

Check XML and HTML responses with the same body(..) and GPath, covering elements and attributes, find and findAll, depth-first search with **, namespaces with and without declareNamespace, and lenient HTML.

Check XML and HTML Responses in REST Assured

Your bank’s statement endpoint doesn’t return JSON. It returns an ISO 20022 statement in XML, the format banks exchange, and an HTML page with the same transactions. A colleague suggests adding an XML library and a separate HTML parser to the test suite. In this guide, you’ll check both with the same body(..) call and the same GPath you’ve used for JSON, and learn the four things that work differently.

Level: Intermediate · Time: 25 minutes · Part of: Module 3: Validating Responses in Depth, section 7

What You’ll Build

You’ll build a test class called XmlAndHtmlTest with five tests. Four check the XML statement: elements and attributes, filters, depth-first search and namespaces. One checks the HTML page.

The XML tests send this request and check this response:

1
2
3
4
5
6
7
GET /api/v1/accounts/acc-1001/statement HTTP/1.1
Host: localhost:<port>

HTTP/1.1 200 OK
Content-type: application/xml; charset=utf-8

<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08" ...><BkToCstmrStmt>...</BkToCstmrStmt></Document>

When you’re done, Maven reports five passing tests:

1
2
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

In this guide, you will:

  • Read XML elements and attributes.
  • Filter and search XML.
  • Match XML namespaces.
  • Check an HTML page.

What You Need

How to Complete This Guide

You can work through this guide in one of two ways:

  • Build it step by step: create XmlAndHtmlTest in a new section_07 package next to the classes from the previous sections, and follow every heading below.
  • Skip ahead: open the finished class (XmlAndHtmlTest.java) and read along. You can run it at any time with the command in Run the Tests.

Get the code: if you haven’t cloned the examples repository yet, follow the steps in Filter JSON Lists With GPath in REST Assured.

Out of scope: this guide doesn’t cover validating XML against a schema, such as the ISO 20022 XSD; that’s taught in Module 6.

Understand GPath on XML and HTML

The problem. Not every API speaks JSON. Banks exchange statements as ISO 20022 XML, SOAP services answer in XML, and some endpoints return HTML. A second library for each format means a second way to write every check, and tests that read differently from the rest of the suite.

The concept. REST Assured looks at the content type. For XML and HTML, it parses the body with XmlPath instead of JsonPath. Paths look the same as for JSON, with four differences:

DifferenceExample
A path starts with the root elementDocument.BkToCstmrStmt... for <Document>..</Document>
@ reads an attributeAmt.@Ccy reads Ccy from <Amt Ccy="EUR">
** searches the whole tree, depth first**.find { it.name() == 'MsgId' }; it.name() is the element’s name
Values are text<Amt>2407.65</Amt> is the string "2407.65"

find, findAll, indexes, size() and root paths work as they do for JSON. HTML uses the same XmlPath, with a lenient parser.

When to use it. Use body(..) with XmlPath for the values a client reads from XML or HTML. Use a full path when an element’s name appears in several places, and depth-first search when only the name matters. For a real web application with JavaScript, use a browser-testing tool instead.

Check XML and HTML with the same paths as JSON, and remember that every value is text.

Meet the API Under Test

This guide uses two endpoints of the Transactions API:

MethodPathPurpose
GET/accounts/{id}/statementThe statement as XML, a simplified ISO 20022 camt.053
GET/accounts/{id}/statement.htmlThe same transactions as an HTML page

The XML statement looks like this, shortened to the first entry:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:camt.053.001.08" xmlns:ext="urn:example:bank:extensions">
  <BkToCstmrStmt>
    <GrpHdr>
      <MsgId>STMT-2026-03</MsgId>
      <CreDtTm>2026-04-01T06:00:00</CreDtTm>
    </GrpHdr>
    <Stmt>
      <Id>acc-1001-2026-03</Id>
      <Acct>
        <Id>
          <IBAN>NL91ABNA0417164300</IBAN>
        </Id>
        <Ccy>EUR</Ccy>
      </Acct>
      <Bal>
        <Tp>OPBD</Tp>
        <Amt Ccy="EUR">1000.00</Amt>
        <CdtDbtInd>CRDT</CdtDbtInd>
      </Bal>
      <Bal>
        <Tp>CLBD</Tp>
        <Amt Ccy="EUR">2407.65</Amt>
        <CdtDbtInd>CRDT</CdtDbtInd>
      </Bal>
      <Ntry>
        <NtryRef>tx-1</NtryRef>
        <Amt Ccy="EUR">2500.00</Amt>
        <CdtDbtInd>CRDT</CdtDbtInd>
        <BookgDt>
          <Dt>2026-03-01</Dt>
        </BookgDt>
        <NtryDtls>
          <RltdPties>
            <Nm>Acme B.V.</Nm>
          </RltdPties>
          <RmtInf>
            <Ustrd>Salary March</Ustrd>
          </RmtInf>
        </NtryDtls>
        <ext:Category>SALARY</ext:Category>
      </Ntry>
      ...
    </Stmt>
  </BkToCstmrStmt>
</Document>

The HTML page holds the same six transactions in a table:

1
2
3
4
5
6
7
8
9
10
11
12
<html>
  <head><title>Statement NL91ABNA0417164300</title></head>
  <body>
    <h1>March 2026</h1>
    <table id="transactions">
<tr><td>2026-03-01</td><td>Acme B.V.</td><td>2500.00</td></tr>
<tr><td>2026-03-02</td><td>Albert Heijn</td><td>-42.35</td></tr>
<tr><td>2026-03-05</td><td>Woonstichting De Key</td><td>-1100.00</td></tr>
...
    </table>
  </body>
</html>

Your tests check these elements:

  • Bal, a balance: OPBD is the opening balance and CLBD the closing balance.
  • Ntry, an entry per transaction. Amounts are positive, and CdtDbtInd says whether it’s a credit (CRDT) or a debit (DBIT).
  • ext:Category, in a second namespace: an extension that isn’t part of the standard.
  • The HTML page’s title, h1 and table rows.

Read XML Elements and Attributes

Set Up the Test Class

Goal: create the test class with a constant for the long path to the statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.javanibble.module_03.section_07;

import static io.restassured.RestAssured.given;
import static io.restassured.config.RestAssuredConfig.config;
import static io.restassured.config.XmlConfig.xmlConfig;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItems;

import com.javanibble.transactions.TransactionsApi;

import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

class XmlAndHtmlTest {

    private static final String STATEMENT = "Document.BkToCstmrStmt.Stmt";

    private static TransactionsApi api;

    @BeforeAll
    static void startApi() {
        api = TransactionsApi.start();
    }

    @AfterAll
    static void stopApi() {
        api.close();
    }

    private static RequestSpecification transactionsApi() {
        return given().baseUri(api.baseUri()).port(api.port()).basePath(TransactionsApi.BASE_PATH);
    }
}

What’s happening:

  • STATEMENT holds the path from the root element to <Stmt>, which most checks start from.
  • xmlConfig is for the namespace step, and ContentType for checking the XML and HTML content types.

Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.

Read Elements, Lists and Attributes

Goal: read single elements, count repeated ones, and read an attribute.

1
2
3
4
5
6
7
8
9
10
11
12
@Test
void elementsAndAttributes() {
    transactionsApi()
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .contentType(ContentType.XML)
        .body("Document.BkToCstmrStmt.GrpHdr.MsgId", equalTo("STMT-2026-03"))
        .body(STATEMENT + ".Acct.Id.IBAN", equalTo(TransactionsApi.IBAN))
        .body(STATEMENT + ".Ntry.size()", equalTo(6))
        .body(STATEMENT + ".Bal[0].Amt.@Ccy", equalTo("EUR"));
}

What’s happening:

  • Every path starts with the root element, Document.
  • Repeated elements form a list: Ntry has six entries, so Ntry.size() is 6, and Bal[0] is the first balance.
  • @Ccy reads the attribute of the Amt element.

Checkpoint: run XmlAndHtmlTest from your IDE. One test runs and passes.

Don’t leave out the root element. For JSON, a path starts inside the body; for XML, it starts with the root. BkToCstmrStmt.GrpHdr.MsgId finds nothing, and the check fails with Actual: <>, an empty result.

Filter and Search XML

Use find and findAll on Elements

Goal: find the closing balance, the debit entries, and the counterparty names.

1
2
3
4
5
6
7
8
9
10
11
@Test
void findAndFindAllWorkOnElements() {
    transactionsApi()
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .rootPath(STATEMENT)
        .body("Bal.find { it.Tp == 'CLBD' }.Amt", equalTo("2407.65"))
        .body("Ntry.findAll { it.CdtDbtInd == 'DBIT' }.NtryRef", contains("tx-2", "tx-3", "tx-4", "tx-5"))
        .body("Ntry.NtryDtls.RltdPties.Nm", hasItems("Acme B.V.", "NS Reizigers"));
}

What’s happening:

  • rootPath(STATEMENT) works on XML too, so the paths start at <Stmt>.
  • it.Tp == 'CLBD' compares the text of a child element.
  • equalTo("2407.65") is a string, because XML values are text.
  • Ntry.NtryDtls.RltdPties.Nm collects the name from every entry, like transactions.id in JSON.

Checkpoint: run the class again. Two tests pass.

Search Depth First

Goal: find elements by name, wherever they are in the document.

1
2
3
4
5
6
7
8
9
@Test
void depthFirstSearch() {
    transactionsApi()
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .body("**.find { it.name() == 'MsgId' }", equalTo("STMT-2026-03"))
        .body("**.findAll { it.name() == 'Ntry' }.size()", equalTo(6));
}

What’s happening:

  • ** visits every element in the document, and it.name() is the element’s name.
  • The path no longer depends on where MsgId sits, so it keeps working when the structure around it changes.

Checkpoint: run the class again. Three tests pass.

Depth-first search gives up precision. If two elements have the same name in different places, find returns the first one: **.find { it.name() == 'Amt' } returns 1000.00, the opening balance, not the first transaction’s 2500.00. Use a full path when a name appears in several places.

Match XML Namespaces

Read an Element in a Second Namespace

Goal: read ext:Category by its local name, and then only in its namespace.

The statement uses two namespaces: the default one, from the ISO 20022 standard, and ext for ext:Category.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void namespaces() {
    transactionsApi()
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .body(STATEMENT + ".Ntry[2].Category", equalTo("RENT"));

    transactionsApi()
        .config(config().xmlConfig(xmlConfig().declareNamespace("ext", "urn:example:bank:extensions")))
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .body(STATEMENT + ".Ntry[2].ext:Category", equalTo("RENT"));
}

What’s happening:

  • Without a declaration, Category matches the element by its local name, whatever its namespace. That’s enough for most tests.
  • With declareNamespace("ext", ..), the path ext:Category matches only Category elements in the namespace urn:example:bank:extensions. Use it when two namespaces have elements with the same name.
  • What counts is the namespace URI, not the prefix in the document: declared as x, the path x:Category works too.

Checkpoint: run the class again. Four tests pass.

A prefix without a declaration matches nothing. Without declareNamespace(..), Ntry[2].ext:Category fails with Actual: <>. Use the local name, or declare the namespace.

Check an HTML Page

Read the Title, Heading and Table

Goal: check an HTML page with full paths, depth-first search and an attribute.

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void html() {
    transactionsApi()
    .when()
        .get("/accounts/{id}/statement.html", TransactionsApi.ACCOUNT_ID)
    .then()
        .contentType(ContentType.HTML)
        .body("html.head.title", equalTo("Statement " + TransactionsApi.IBAN))
        .body("html.body.h1", equalTo("March 2026"))
        .body("**.findAll { it.name() == 'tr' }.size()", equalTo(6))
        .body("**.findAll { it.name() == 'tr' }[2].td[1]", equalTo("Woonstichting De Key"))
        .body("**.find { it.@id == 'transactions' }.name()", equalTo("table"));
}

What’s happening:

  • Full paths such as html.head.title work for the fixed parts of a page.
  • **.findAll { it.name() == 'tr' } finds the table rows wherever they are, and [2].td[1] reads the second cell of the third row.
  • it.@id == 'transactions' finds an element by an attribute, like a CSS id selector.

Checkpoint: run the class again. All five tests pass.

On this page the rows sit directly inside <table>, so html.body.table.tr works too. Many pages wrap rows in a <tbody>, and a full path then finds nothing. A depth-first search for tr doesn’t depend on that structure, which makes it the safer choice for tables.

Run the Tests

Run the following command from the repository root:

1
mvn test -pl module-03 -Dtest=XmlAndHtmlTest

You should see a result similar to the following:

1
2
3
4
5
6
[INFO] Running com.javanibble.module_03.section_07.XmlAndHtmlTest
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.538 s -- in com.javanibble.module_03.section_07.XmlAndHtmlTest
[INFO]
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

Make a Test Fail

In findAndFindAllWorkOnElements, change equalTo("2407.65") to equalTo(2407.65f) and run the command again. You should see a result similar to the following:

1
2
3
4
5
[ERROR] Failures:
[ERROR]   XmlAndHtmlTest.findAndFindAllWorkOnElements:70 1 expectation failed.
XML path Document.BkToCstmrStmt.Stmt.Bal.find { it.Tp == 'CLBD' }.Amt doesn't match.
Expected: <2407.65F>
  Actual: 2407.65

The message starts with XML path, not JSON path, so you know XmlPath read the body. The expected value is a Float, with the F and angle brackets, while the actual value has neither: it’s the text 2407.65. For JSON the default would have been a Float; for XML every value is a string.

Change equalTo(2407.65f) back to equalTo("2407.65") and run the tests once more to confirm they pass.

Troubleshooting

SymptomLikely causeFix
Expected: <2407.65F> but Actual: 2407.65An XML value was compared with a numberCompare with a string
Actual: <> for a path you expected to matchThe root element is missing from the path, or a prefix isn’t declaredStart with the root element, or use declareNamespace(..)
A depth-first find returns the wrong elementSeveral elements have that nameUse a full path
A full path into an HTML table finds nothingThe rows are wrapped in a <tbody>Search for tr depth first

Try It Yourself

Exercise 1: Check the Rent Entry

Add a test called theRentEntry that sets a root path to the entry whose NtryRef is tx-3, and checks its amount "1100.00", the amount’s currency attribute "EUR", the indicator "DBIT", the counterparty name "Woonstichting De Key" and the booking date "2026-03-05".

Hint

Combine STATEMENT with Ntry.find { it.NtryRef == 'tx-3' } in rootPath(..). The amount is positive in XML; CdtDbtInd carries the sign.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void theRentEntry() {
    transactionsApi()
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .rootPath(STATEMENT + ".Ntry.find { it.NtryRef == 'tx-3' }")
        .body("Amt", equalTo("1100.00"))
        .body("Amt.@Ccy", equalTo("EUR"))
        .body("CdtDbtInd", equalTo("DBIT"))
        .body("NtryDtls.RltdPties.Nm", equalTo("Woonstichting De Key"))
        .body("BookgDt.Dt", equalTo("2026-03-05"));
}

Exercise 2: Check the Statement and the Page Together

Add a test called theStatementAndThePageAgree. With the ext namespace declared, check that the statement has four CdtDbtInd elements with the value DBIT, found depth first; that the entries’ ext:Category values include SALARY, RENT and REFUND; and that the balance types are OPBD and CLBD, in that order. Then check that the HTML table’s counterparty column includes "Acme B.V." and "Belastingdienst".

Hint

A depth-first closure can test both the name and the text, as in it.name() == '..' && it == '..'. For the HTML column, collect { it.td[1] } reads the second cell of every row; .td[1] after findAll alone indexes the whole list instead.

Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
void theStatementAndThePageAgree() {
    transactionsApi()
        .config(config().xmlConfig(xmlConfig().declareNamespace("ext", "urn:example:bank:extensions")))
    .when()
        .get("/accounts/{id}/statement", TransactionsApi.ACCOUNT_ID)
    .then()
        .body("**.findAll { it.name() == 'CdtDbtInd' && it == 'DBIT' }.size()", equalTo(4))
        .body(STATEMENT + ".Ntry.ext:Category", hasItems("SALARY", "RENT", "REFUND"))
        .body(STATEMENT + ".Bal.Tp", contains("OPBD", "CLBD"));

    transactionsApi()
    .when()
        .get("/accounts/{id}/statement.html", TransactionsApi.ACCOUNT_ID)
    .then()
        .body("**.findAll { it.name() == 'tr' }.collect { it.td[1] }", hasItems("Acme B.V.", "Belastingdienst"));
}

Summary

You built XmlAndHtmlTest, which checks an ISO 20022 XML statement and an HTML page with the same body(..) and GPath you use for JSON. No second library joined the suite.

  • REST Assured parses XML and HTML with XmlPath, chosen from the content type, so body(..) works as it does for JSON.
  • A path starts with the root element, @ reads an attribute, and every value is text.
  • ** searches the whole tree depth first; use a full path when an element’s name appears in several places.
  • Without a declared namespace, a path matches elements by their local name; XmlConfig.declareNamespace(..) makes a prefixed path match one namespace only.
  • HTML is parsed the same way; for tables, a depth-first search for tr doesn’t depend on whether the rows sit in a <tbody>.

Here are the commands you used in this guide:

1
mvn test -pl module-03 -Dtest=XmlAndHtmlTest

What’s Next

Next: you’ve completed Module 3. Continue with Module 4: Extracting Values and Mapping Objects, starting with Extract Values From a Response in REST Assured, which takes values out of a response for use in Java and in the next request.

The code:

Go deeper:

Related guides:

This post is licensed under CC BY 4.0 by the author.