Skip to main content

XML

XML is a first-class type in Ballerina with built-in support for XML literals, namespaces, and navigation. The ballerina/data.xmldata module (v1.6.2) provides type-safe record binding, XPath transforms, JSON conversion, and XSD validation.

Module

Built-in (no import needed for basic operations); ballerina/data.xmldata for record binding and transforms.

Usage

Create and navigate XML

// XML literal — no imports needed
xml purchaseOrder = xml `
<order id="ORD-001">
<item name="Widget" qty="10" price="9.99"/>
<item name="Gadget" qty="2" price="24.99"/>
</order>`;

// XPath-like navigation
xml items = purchaseOrder/<item>;
string name = check (purchaseOrder/<item>).first().name;

XML to record binding

import ballerina/data.xmldata;

type XMLOrder record {|
@xmldata:Attribute
string id;
XMLItem[] item;
|};

type XMLItem record {|
@xmldata:Attribute
string name;
@xmldata:Attribute
int qty;
@xmldata:Attribute
decimal price;
|};

string xmlString = "<order id=\"ORD-001\"><item name=\"Widget\" qty=\"10\" price=\"9.99\"/></order>";
XMLOrder typedOrder = check xmldata:parseString(xmlString);

Parse from bytes and streams

import ballerina/data.xmldata;
import ballerina/io;

// Parse from byte array
byte[] xmlBytes = "<config><port>8080</port></config>".toBytes();
record {int port;} cfg = check xmldata:parseBytes(xmlBytes);

// Parse from a byte stream
stream<byte[], io:Error?> byteStream = check io:fileReadBlocksAsStream("data.xml");
record {} data = check xmldata:parseStream(byteStream);

Record to XML

import ballerina/data.xmldata;

type Address record {|
@xmldata:Attribute
string type;
string street;
string city;
|};

Address addr = {'type: "home", street: "123 Main St", city: "Springfield"};
xml addressXml = check xmldata:toXml(addr);

JSON to XML conversion

import ballerina/data.xmldata;

json order = {
orderId: "ORD-001",
items: [{name: "Widget", qty: 10}]
};

xml orderXml = check xmldata:fromJson(order);

XPath transform

import ballerina/data.xmldata;

xml catalog = xml `
<catalog>
<book><title>Clean Code</title><price>33.99</price></book>
<book><title>Refactoring</title><price>42.50</price></book>
</catalog>`;

string title = check xmldata:transform(catalog, `/catalog/book[1]/title/text()`);
// title: "Clean Code"

XSD validation

import ballerina/data.xmldata;

xml doc = xml `<order><id>123</id></order>`;

// Validate against an XSD file
xmldata:Error? err = xmldata:validate(doc, "resources/order.xsd");

// Or validate against a record type
xmldata:Error? err2 = xmldata:validate(doc, Order);

Functions

FunctionSignatureDescription
parseStringparseString(string s, SourceOptions options = {}, typedesc<record {}> t = <>) returns t|ErrorParse an XML string into a typed record.
parseBytesparseBytes(byte[] s, SourceOptions options = {}, typedesc<record {}> t = <>) returns t|ErrorParse an XML byte array into a typed record.
parseStreamparseStream(stream<byte[], error?> s, SourceOptions options = {}, typedesc<record {}> t = <>) returns t|ErrorParse an XML byte stream into a typed record.
parseAsTypeparseAsType(xml v, SourceOptions options = {}, typedesc<record {}> t = <>) returns t|ErrorConvert an xml value into a typed record.
toXmltoXml(map<anydata> mapValue, Options options = {}) returns xml|ErrorConvert a record or map to XML.
fromJsonfromJson(json jsonValue, JsonOptions options = {}) returns xml|ErrorConvert a JSON value to XML.
transformtransform(xml xmlValue, XPathRawTemplate query, typedesc<anydata> td = <>) returns td|ErrorTransform XML using an XPath query.
validatevalidate(xml xmlValue, string|typedesc<record {}> schema) returns Error?Validate XML against an XSD file or record type.

Options

SourceOptions

FieldTypeDefaultDescription
attributePrefixstring""Prefix for attribute field names.
textFieldNamestring"#content"Field name for text content nodes.
allowDataProjectionbooleantrueWhether to allow data projection.
useSemanticEqualitybooleantrueWhether to use semantic equality for matching.
enableConstraintValidationbooleantrueWhether to validate constraints on the target type.

JsonOptions

FieldTypeDefaultDescription
attributePrefixstring"@"Prefix for attribute keys in JSON input.
arrayEntryTagstring"item"XML element name for JSON array entries.
rootTagstring?()Root element name.
textFieldNamestring"#content"JSON key that maps to XML text content.

Annotations

AnnotationDescription
@xmldata:NameOverrides the XML element or field name.
@xmldata:NamespaceSpecifies namespace prefix and URI. Takes prefix and uri parameters.
@xmldata:AttributeMarks a record field as an XML attribute.
@xmldata:ElementDefines XSD element constraints (minOccurs, maxOccurs).
@xmldata:SequenceDefines XSD sequence constraints.
@xmldata:ChoiceDefines XSD choice constraints.
@xmldata:SequenceOrderDefines sequence ordering.