-
Notifications
You must be signed in to change notification settings - Fork 4
Use Case: Serializing an Object According to an XML Schema
Consider a file xs.xsd containing an XML Schema with a fragment
<xs:element name="ExportDebtRequestsResponse">
<xs:annotation>
<xs:documentation>Blah-blah</xs:documentation>
</xs:annotation>
<xs:complexType>
<xs:choice>
<xs:sequence>
<xs:element name="request-data" type="tns:ExportDebtRequestType" maxOccurs="unbounded">
<!-- ... and so on ... -->and a plain js Object
const data = {ExportDebtRequestsResponse: {
"request-data": {
// ...
}
}The goal is to obtain the valid XML text representing the data object according to the schema definition.
const {XMLSchemata} = require ('xml-toolkit')
const xs = new XMLSchemata ('xs.xsd')
const xml = xs.stringify (data)
/* result:
<ns0:ExportDebtRequestsResponse xmlns:ns0="urn:...">
<ns0:request-data>
<!-- ... and so on ... -->
*/Here:
- an XMLSchemata instance is created by loading the given file;
- its
stringifymethod does the job by:- looking up the schema element by the root object key (
ExportDebtRequestsResponse) - creating a temporary XMLMarshaller
- invoking its
stringifymethod that actually concatenates the XML string.
- looking up the schema element by the root object key (
Unfortunately, no: xml-toolkit supports only a limited subset of w3c specifications.
It should cover most real life data centric cases though.
See the Limitations section for details.
It writes right tags and attributes with right qualified names and fills them up with content taken from data.
Scalar values are transformed according to simpleTypes and some restrictions: i. e. numbers in decimal fields with fractionDigits set are serialized with toFixed. See the corresponding section for details.
The invalid XML may occur as a result of incorrectly prepared data: choice ambiguities, maxOccurs overflows, key violations etc.
This the Greek plural ending. The word "schemata" is plural for "schema", in Greek and in English.
In xml-toolkit:
- XMLSchema represents a single target namespace;
-
XMLSchemata is a map of namespace URIs to the corresponding instances of
XMLSchema.
It's always possible to create an XMLMarshaller explicitly, using the necessary namespace URI.
XMLSchemata's stringify is only a top level wrapper.
As it is mentioned in limitations:
-
xs:imports are supported- but for relative links only
-
xs:includes are not yet.
The locally linked set of offline files is essential for run time usage anyway: external http references are not to use at run time in production.