XML Structure

Introduction

Before JSON became the dominant format for REST APIs, XML was the standard format for exchanging structured data between systems. XML stands for eXtensible Markup Language. It has been used for decades in SOAP web services, banking systems, healthcare applications, insurance platforms, government systems, enterprise integrations, payment gateways, legacy applications, and document-driven workflows. Even today, many important business APIs still use XML for requests, responses, configuration files, service contracts, and message exchange.

XML and JSON both represent structured data, but they use very different syntax. JSON uses objects, arrays, keys, and values. XML uses tags, elements, attributes, hierarchy, declarations, namespaces, and schemas. A JSON object may represent an employee with fields such as id and name. An XML document represents similar data using opening and closing tags such as <Employee>, <Id>, and <Name>. This makes XML more verbose than JSON, but also very expressive for document-like and enterprise integration scenarios.

For API testers, understanding XML structure is still valuable. A tester may work with SOAP services, legacy banking APIs, XML-based payment integrations, healthcare data exchange, insurance claims, government reporting, or older enterprise middleware. Even when a project mostly uses JSON, testers may still encounter XML in third-party integrations, configuration, message queues, or reports. A tester who understands XML can validate requests, inspect responses, diagnose parsing errors, verify XSD compliance, and write stronger automation for XML-based APIs.

This tutorial explains XML structure from a practical API testing perspective. It covers XML documents, declarations, root elements, child elements, parent-child relationships, opening and closing tags, element content, nested elements, repeating elements, empty elements, attributes, attributes versus elements, complete XML examples, XML in API requests, XML in API responses, well-formed rules, XML validation, REST Assured, Postman, Karate, SOAP messages, XSD validation, namespaces, best practices, common mistakes, and interview-ready explanations.

What Is XML?

XML is a markup language used to store, organize, and transport structured data between applications. Unlike HTML, XML does not provide a fixed set of predefined tags for display. Developers define their own tags based on the business data they need to represent. For example, an employee system may use <Employee>, <Name>, and <Department>, while a banking system may use <Account>, <Balance>, and <Transaction>.

In simple terms, XML represents structured data using custom tags and hierarchical elements. A tag describes what the data means, and the content between tags contains the value. Because XML is self-descriptive, a person reading the document can often understand the meaning of the data without separate column headings or hidden metadata.

XML is platform independent. A Java service, .NET service, Python application, mainframe integration, or enterprise middleware system can exchange XML because XML is text-based and standardized. This is one reason XML remains common in enterprise systems where many technologies need to communicate reliably.

Why XML Is Used

XML is used because it provides structured data representation, platform independence, self-descriptive data, strong support for hierarchical information, and powerful validation through XSD, which stands for XML Schema Definition. XML can represent simple records, complex nested documents, repeating sections, metadata, attributes, and namespaced service messages.

In SOAP web services, XML is not optional; SOAP messages are XML documents. The SOAP envelope, header, and body follow XML structure. Many banking and insurance systems still rely on SOAP because of legacy contracts, formal schemas, security extensions, and enterprise tooling. Healthcare and government systems also use XML because schemas and strict validation are important for regulated data exchange.

XML is more verbose than JSON, but that verbosity can be useful when messages need rich structure, metadata, namespaces, and formal validation. For testers, the important point is not whether XML is newer or older than JSON. The important point is that XML still appears in many real systems, and testers must be able to validate it correctly.

Basic XML Structure

A basic XML document may look like this:

<?xml version="1.0" encoding="UTF-8"?>

<Employee>
  <Id>101</Id>
  <Name>John</Name>
</Employee>

This document contains an XML declaration, a root element, and child elements. The declaration tells processors the XML version and character encoding. The root element is Employee. The child elements are Id and Name. Each child element has opening and closing tags, and the value appears between those tags.

The structure can be understood as a tree. The root is the top-level node. Child elements appear under the root. Nested elements appear under their parent elements. This tree-based structure is central to XML parsing, XPath navigation, XSD validation, and API response testing.

XML Document Structure

An XML document commonly follows a simple organization: XML declaration, root element, child elements, nested elements, and closing tags. The declaration may appear at the beginning. The root element contains everything else. Child elements describe data inside the root. Nested elements add hierarchy. Closing tags complete each element.

Unlike JSON, XML requires one top-level root element. A document cannot have two separate root elements side by side. All other elements must be contained inside that one root. This rule is important because many XML parsing errors occur when a document has extra content outside the root or multiple root-level elements.

For API testing, the structure should match the service contract. If the response is expected to return Employee as the root element, returning User instead may break consumers. If required child elements are missing, the response may be well-formed XML but still fail contract validation.

XML Declaration

Many XML documents begin with an XML declaration:

<?xml version="1.0" encoding="UTF-8"?>

The declaration specifies the XML version and character encoding. The version is commonly 1.0. The encoding is commonly UTF-8. Encoding tells the parser how to interpret characters in the document. This matters for names, addresses, special symbols, international text, and documents exchanged across systems.

The XML declaration is optional in many contexts, but it is commonly included in formal documents and enterprise integrations. Testers should know whether the API contract expects it. If encoding is incorrect or missing where required, parsing or downstream processing may fail, especially when special characters are present.

Root Element

Every XML document must have exactly one root element. The root element contains all other elements in the document. For example:

<Employee>
</Employee>

Here, Employee is the root element. All employee data must appear inside it. A complete document may include child elements inside the root:

<Employee>
  <Id>101</Id>
  <Name>John</Name>
</Employee>

If an XML document has no root element or has multiple root elements, it is not well-formed. This is one of the most important XML rules. In API testing, root element validation confirms that the response begins with the expected business structure or SOAP structure.

Child Elements

Elements inside the root element are child elements. In this example, Id and Name are child elements of Employee:

<Employee>
  <Id>101</Id>
  <Name>John</Name>
</Employee>

Child elements represent fields or substructures. They may contain text values, attributes, or nested child elements of their own. The meaning of child elements is defined by the API contract or XML schema.

For testers, child element validation includes checking whether required child elements exist, optional child elements behave correctly, values are correct, data types are valid according to XSD, element order is correct if order matters, and unexpected elements are handled according to the contract.

Parent and Child Relationship

XML data is hierarchical. Elements can contain other elements, creating parent-child relationships. For example:

<Employee>
  <Address>
    <City>Chicago</City>
  </Address>
</Employee>

In this structure, Employee is the parent of Address, and Address is the parent of City. The path to the city value is conceptually Employee/Address/City. XPath and XML path tools use this hierarchy to locate values.

Parent-child relationships should reflect business meaning. Address belongs to employee. Items belong to order. Transactions belong to account. When the hierarchy is wrong, XML may still be well-formed, but the business structure is incorrect. API tests should validate both technical structure and business relationships.

Opening and Closing Tags

Most XML elements have an opening tag and a closing tag. The opening tag starts the element, and the closing tag ends it. The closing tag uses the same name with a slash.

<Name>John</Name>

Here, <Name> is the opening tag, John is the element content, and </Name> is the closing tag. Every opening tag must have a matching closing tag unless the element is self-closing.

Tag names are case-sensitive. <Name> and </name> do not match. This is different from HTML parsing behavior in browsers, where tag handling can be more forgiving. XML parsers are strict, which is why small tag mistakes can break an entire XML API response.

Element Content

Element content is the data between opening and closing tags. For example:

<Department>QA</Department>

The element is Department, and the value is QA. Element content can be text, numbers represented as text, dates, codes, or nested elements. XML itself stores content as text, but XSD can define expected data types such as string, integer, decimal, boolean, date, and dateTime.

API testers should validate both the presence and meaning of element content. A Balance element may exist, but its value may be blank, invalid, negative, incorrectly formatted, or outside the allowed range. XSD validation and business assertions work together here.

Nested Elements

XML supports nested elements. Nested elements allow XML documents to represent hierarchical business data:

<Employee>
  <Address>
    <City>Chicago</City>
    <State>Illinois</State>
  </Address>
</Employee>

This structure has an employee element, an address element inside employee, and city and state elements inside address. The hierarchy is easy to understand because indentation shows parent and child levels.

Nested elements are common in XML APIs. A customer can contain contact details. An order can contain shipping address and line items. A SOAP body can contain an operation request, which contains business data. Testers should validate every important level of nesting instead of checking only top-level elements.

Multiple Child Elements

A root element can contain multiple child elements. For example:

<Employee>
  <Id>101</Id>
  <Name>John</Name>
  <Department>QA</Department>
</Employee>

This employee contains ID, name, and department. In XML APIs, these child elements may be mandatory or optional depending on the schema. Some schemas also require elements to appear in a specific order. If the order is wrong, XSD validation may fail even when all elements are present.

For API testing, multiple child elements should be validated for existence, order when required, values, data types, empty values, optional behavior, and missing-field behavior. XML is often stricter than JSON when schemas define element order.

Repeating Elements

XML represents collections using repeating elements. For example, a list of employees can be represented as multiple Employee elements inside an Employees root:

<Employees>
  <Employee>
    <Name>John</Name>
  </Employee>
  <Employee>
    <Name>Alice</Name>
  </Employee>
</Employees>

Each Employee element represents one record. The parent Employees element represents the collection. This is similar to a JSON array of objects, but XML expresses it through repeated tags rather than square brackets.

Testing repeating elements includes checking count, required child elements in each item, duplicate records, ordering, filtering behavior, empty collection behavior, and schema limits such as minimum and maximum occurrences. XPath can be used to access specific repeated elements or loop through them in automation.

Empty Elements

XML allows empty elements. An empty element can be written with separate opening and closing tags:

<MiddleName></MiddleName>

It can also be written as a self-closing tag:

<MiddleName/>

Both forms represent an element with no content. However, the business meaning should be defined. Empty may mean no value, intentionally blank, not applicable, or unknown depending on the field and system. XML can also use attributes or schema rules to define null-like behavior, especially in SOAP and XSD-based systems.

Testers should validate whether empty elements are allowed, whether required elements can be empty, whether optional elements should be omitted instead, and whether empty values are interpreted correctly by the API.

XML Attributes

XML elements can contain attributes. Attributes provide additional information inside an element's opening tag. For example:

<Employee id="101">
  <Name>John</Name>
</Employee>

Here, id="101" is an attribute of the Employee element. The Name element is a child element. Attribute values must be enclosed in quotes. XML attributes are commonly used for identifiers, metadata, type information, namespace declarations, language codes, and flags.

For API testing, attribute validation includes checking required attributes, optional attributes, attribute values, quoted values, data types according to schema, namespace attributes, and whether values should be represented as attributes or elements based on the contract.

Attributes vs Elements

The same information can sometimes be represented as an element or an attribute. As an element:

<Employee>
  <Id>101</Id>
</Employee>

As an attribute:

<Employee id="101"/>

Both are valid XML, but they are not the same structure. The API contract determines which is correct. A client expecting <Id> as a child element may not read id as an attribute. A schema expecting an attribute may reject a child element.

As a general design guideline, elements are often used for main business data, while attributes are often used for metadata. However, real systems vary. Testers should validate according to the WSDL, XSD, API documentation, or agreed contract.

Complete XML Example

A complete employee XML document may look like this:

<?xml version="1.0" encoding="UTF-8"?>

<Employee>
  <Id>101</Id>
  <Name>John</Name>
  <Department>QA</Department>
  <Address>
    <City>Chicago</City>
    <State>Illinois</State>
  </Address>
</Employee>

This document has a declaration, one root element, multiple child elements, and a nested address element. Its tree structure is Employee at the top, with Id, Name, Department, and Address below it. Address has City and State below it.

A tester can validate that the XML is well-formed, the root is Employee, required elements exist, nested address fields are present, values are correct, and the document matches the XSD if one is available. This is the same layered thinking used in JSON testing: syntax, structure, schema, and business behavior.

XML in API Requests

Some APIs accept XML request bodies. A request may look like this:

POST /employee
Content-Type: application/xml

<Employee>
  <Name>John</Name>
  <Department>QA</Department>
</Employee>

The server parses the XML, validates the structure, checks required elements, and applies business rules. If the XML is malformed, parsing should fail. If the XML is well-formed but violates the XSD, schema validation should fail. If the XML is structurally valid but violates business rules, the API should return a business validation error.

Request testing should include valid XML, missing required elements, empty elements, invalid element order, wrong root element, invalid attributes, malformed tags, namespace issues, wrong content type, and invalid business values.

XML in API Responses

APIs that return XML usually use Content-Type: application/xml or a related XML media type. A response may look like this:

HTTP/1.1 200 OK
Content-Type: application/xml

<Employee>
  <Id>101</Id>
  <Name>John</Name>
</Employee>

The tester should validate status code, content type, well-formed XML, root element, child elements, values, attributes, namespaces if used, XSD compliance, and business rules. A response that returns 200 OK but malformed XML is defective if the endpoint promises XML.

XML responses should also avoid exposing sensitive internal data. Just like JSON, XML may accidentally include passwords, internal IDs, debug traces, or private configuration. API testers should inspect response content, not only structure.

XML Structure Validation

XML structure validation checks whether the document is well-formed and matches the expected hierarchy. QA engineers should verify that XML is well-formed, the root element exists, tags are properly nested, opening and closing tags match, required elements are present, optional elements behave correctly, attributes are valid, data values are correct, and XSD compliance is satisfied when a schema is available.

Well-formed XML means the document follows basic XML syntax rules. Valid XML usually means it also conforms to an XML schema or DTD. In API testing, both ideas matter. A document can be well-formed but invalid against the schema. For example, all tags may close correctly, but a required Id element may be missing.

Structure validation should be combined with business validation. XSD can confirm that Balance is a decimal, but a business test confirms that the balance changed correctly after a transaction. The schema protects the format; business assertions protect behavior.

XML Well-Formed Rules

A well-formed XML document must have exactly one root element, close all tags correctly, nest elements properly, use case-sensitive matching tag names, quote attribute values, and avoid overlapping tags. These rules are strict. Unlike HTML, XML parsers do not try to fix broken markup automatically.

A missing closing tag is invalid:

<Employee>
  <Name>John
</Employee>

The Name element is never closed. Improper nesting is also invalid:

<Employee>
  <Address>
</Employee>
</Address>

The Address tag opens inside Employee but closes after Employee. Tags must close in the reverse order in which they opened. This stack-like rule is fundamental to XML parsing.

XML Validation in API Testing

API testers should validate root element, child elements, attributes, data values, element order if required by the schema, namespaces if used, XML Schema Definition compliance, and business rules. XML validation is especially important for SOAP services because SOAP messages usually have strict envelope and body structure.

When validating XML manually, testers can inspect formatted XML in tools such as Postman, SoapUI, browser views, IDEs, or XML validators. In automation, testers can use XPath, XMLPath, schema validation, and parsing libraries. The exact tool depends on the project stack.

Tests should be designed around the API contract. If the XSD requires a field, missing that field should fail. If the schema defines element order, wrong order should fail. If the API uses namespaces, XPath expressions must account for them. XML validation can become frustrating when namespaces are ignored, so testers should learn the namespace rules of the service they are testing.

REST Assured Example

REST Assured supports XML path expressions for XML responses. A simple validation may look like this:

given()
.when()
  .get("/employee/101")
.then()
  .body("Employee.Name", equalTo("John"));

This assertion checks the Name element inside the Employee root. REST Assured can also validate attributes and nested elements using XMLPath expressions. For SOAP or complex XML, additional configuration may be needed for namespaces.

Good REST Assured XML tests should verify content type, status code, important elements, attributes, and schema compliance where possible. If the response is not XML or is malformed, the XML parser may fail before assertions complete.

Postman Example

Postman can send XML request bodies by choosing raw body and setting the format or content type to XML. It can display XML responses in a readable form. Basic status validation may look like this:

pm.test("Response status is 200", function () {
  pm.response.to.have.status(200);
});

For detailed XML validation, Postman test scripts may parse XML using XML-to-JSON conversion or supported libraries depending on the environment. Many testers also use SoapUI or specialized XML tools when working heavily with SOAP services.

Postman is useful for exploratory XML API testing, but automated regression should include repeatable checks for structure, required elements, values, and schema rules. Visual inspection alone is not enough for important integrations.

Karate Example

Karate supports XPath-like navigation for XML. A simple check may look like this:

Then match response/Employee/Name == 'John'

This validates the Name element under Employee. Karate can also work with SOAP requests and XML payloads, making it useful for teams that test both REST and SOAP services.

When XML uses namespaces, XPath expressions need to be written with namespace awareness. This is a common source of test failures. Testers should inspect the actual response and understand namespace prefixes before writing final assertions.

SOAP Request Structure

SOAP messages are XML documents. A SOAP request commonly contains an envelope, optional header, and body. The body contains the actual operation request. A simplified SOAP structure looks like this:

<soap:Envelope>
  <soap:Header>
  </soap:Header>
  <soap:Body>
    ...
  </soap:Body>
</soap:Envelope>

SOAP services are often strict about namespaces, operation names, element order, required fields, and schema definitions. A request can fail if a namespace is wrong, a required element is missing, or an element appears in the wrong place.

API testers working with SOAP should validate the full message structure, not only the business values. They should also understand WSDL and XSD artifacts because those define the service contract.

XSD Validation

XSD, or XML Schema Definition, defines the allowed structure and data rules for XML documents. It can specify root elements, child elements, attributes, element order, data types, required fields, optional fields, repeating elements, namespaces, and value restrictions. XSD plays a similar contract role for XML that JSON Schema plays for JSON.

XSD validation is important in enterprise APIs because it catches structural and type defects. An XML document may be well-formed but fail XSD validation because a required element is missing, an element appears in the wrong order, a value has the wrong type, or an unexpected element is present.

In API testing, XSD validation should be used when schemas are available. It provides broad contract coverage, while targeted XPath or XMLPath assertions verify business values. Together, they create stronger XML API tests.

Namespaces in XML Structure

XML namespaces prevent naming conflicts when documents combine elements from different vocabularies. They are common in SOAP services and enterprise XML messages. A namespace prefix may appear before element names, such as soap:Envelope. The prefix maps to a namespace URI declared in the document.

Namespaces can make XML validation and XPath more complex. A tester may see an element named Name, but the actual qualified name includes a namespace. XPath expressions that ignore namespaces may fail even when the element exists.

When testing XML APIs, always inspect namespace declarations and understand whether assertions need namespace-aware paths. Namespace mistakes are common causes of false failures in SOAP testing and XML automation.

Real-World Examples

An employee XML response may look like this:

<Employee>
  <Name>John</Name>
</Employee>

A banking XML response may represent account data:

<Account>
  <Balance>2500</Balance>
</Account>

An order XML response may contain order identity:

<Order>
  <OrderId>5001</OrderId>
</Order>

A SOAP request is also XML:

<soap:Envelope>
  <soap:Body>
    ...
  </soap:Body>
</soap:Envelope>

Each example uses tags and hierarchy to represent structured data. The tester's job is to verify that the XML is well-formed, follows the expected contract, and carries the correct business values.

Best Practices

Always create well-formed XML. Use meaningful element names. Keep XML hierarchy simple and logical. Close every tag correctly. Quote all attribute values. Use attributes only for metadata when appropriate. Validate XML against its XSD when available. Follow consistent naming conventions. Keep XML examples readable with indentation.

For request testing, set the correct content type and send well-formed XML. Validate that the API rejects malformed XML, missing required elements, wrong root elements, invalid attributes, wrong namespaces, and schema violations. For response testing, validate status code, content type, XML structure, required elements, optional behavior, attributes, namespaces, XSD compliance, and business data.

For automation, avoid relying only on plain string matching. Use XML-aware tools such as XPath, XMLPath, or schema validators. String matching can be fragile because whitespace, formatting, and namespace prefixes may vary while the XML meaning remains the same. XML-aware validation is more reliable.

Common Mistakes

A common mistake is missing closing tags. Every opening tag must have a matching closing tag unless it is self-closing. Another mistake is creating multiple root elements:

<Employee></Employee>
<Department></Department>

An XML document can have only one root element, so this structure is invalid. Improper nesting is another frequent issue:

<Employee>
  <Address>
</Employee>
</Address>

Tags must be properly nested. Unquoted attribute values are also invalid:

<Employee id=101>

The correct version quotes the attribute value:

<Employee id="101">

Case mismatch is another common XML problem. <Name>John</name> is invalid because XML is case-sensitive. Skipping namespace handling and XSD validation are also common testing gaps in XML APIs.

Interview Questions

A common interview question is: what is XML? A strong answer is that XML, or eXtensible Markup Language, is a markup language used to store, organize, and exchange structured data using custom tags and hierarchical elements.

Another question is: what is the root element? The root element is the single top-level element that contains all other elements in an XML document. Every well-formed XML document must have exactly one root element.

Interviewers may ask the difference between an element and an attribute. An element stores main data between opening and closing tags or contains nested elements. An attribute provides additional information inside an element's opening tag. Both can carry data, but the schema and design decide which is appropriate.

They may also ask what testers should validate in XML. A strong answer includes well-formed structure, root element, child elements, proper nesting, matching tags, attributes, namespaces, required elements, optional elements, data values, XSD validation, content type, and business rules.

Interview-Ready Explanation

XML structure refers to the hierarchical organization of an XML document using elements, attributes, and nested tags. An XML document may begin with an XML declaration that defines version and encoding. It must contain exactly one root element, and all other child elements must be placed inside that root. Elements are represented using opening and closing tags, and they may contain text, attributes, or other nested elements.

XML documents must be well-formed. This means there must be one root element, every tag must be properly closed, elements must be correctly nested, tag names are case-sensitive, and attribute values must be enclosed in quotes. XML can also be validated against an XSD, which defines required elements, optional elements, data types, element order, attributes, namespaces, and value restrictions.

During API testing, XML requests and responses should be validated for well-formedness, content type, root element, element hierarchy, required fields, optional fields, attributes, data values, namespace usage, XSD compliance, and business rules. XML is especially important in SOAP services and enterprise integrations, where strict structure and schema validation are common.

Key Takeaway

XML remains important in API testing because many enterprise systems still use it for structured communication. It represents data using custom tags, elements, attributes, and hierarchy. Unlike JSON, XML documents must have exactly one root element and must follow strict well-formed rules for tag closure, nesting, case sensitivity, and quoted attributes.

For API testers, the practical rule is to validate XML in layers. First confirm the response is XML and is well-formed. Then validate the expected root, child elements, attributes, namespaces, and hierarchy. Next validate XSD compliance when a schema is available. Finally, validate business rules and values. This approach helps testers handle SOAP services, legacy APIs, and XML-based integrations with confidence and precision.