validateXML
To validate XML documents against an XSD schema
The validateXML
function checks whether a given XML string conforms to the rules defined by an XSD schema. It reads the schema from a file attached to a record and returns a JSON object containing the validation result and any errors found.
This function is especially useful for validating data received from external sources, such as web services or APIs, ensuring data integrity before further processing.
Caution: If the file doesn't contain a valid XSD schema, the function returns
void
.
Syntax
validateXML(record, xmlText, xsdFilename)
Parameters
- record: The source record containing the attached XSD schema file.
- xmlText: The XML string to validate.
- xsdFilename: The name of the XSD schema file attached to the record.
Return
JSON: A JSON object containing the validation result (true
or false
) and any errors encountered during validation.
Examples
1. Valid XML string
let xsd := ---
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:simpleType name="ordertype">
<xs:restriction base="xs:string"/>
</xs:simpleType>
<xs:element name="order" type="ordertype"/>
</xs:schema>
---;
let xsdFilename := "validation.xsd";
let xsdFile := createTextFile(this, xsd, xsdFilename);
let xmlString := ---
<?xml version="1.0" encoding="UTF-8"?>
<order
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="order.xsd">
</order>
---;
formatJSON(validateXML(this, xmlString, xsdFilename));
Result:
{"result":true,"errors":[]}
2. Invalid XML string
xmlString := ---
<?xml version="1.0" encoding="UTF-8"?>
<order id="123"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="order.xsd">
</order>
---;
formatJSON(validateXML(this, xmlString, xsdFilename));
Result:
"result":false,"errors":
[{"domain":17,"code":1827,"level":2,"column":0,"file":"","line":4,"str1":"id"}]}
See also
formatJSON
which creates a JSON string of a valid JSON object.
parseXML
which converts an XML string to a JSON object.
formatXML
which converts a given JSON object into XML text, which might be optically structured.