Skip to content

Use Case: Serializing an Object According to an XML Schema

do- edited this page Nov 5, 2022 · 3 revisions

Input

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": {
   // ...
  }
}

Problem

The goal is to obtain the valid XML text representing the data object according to the schema definition.

Basic Solution

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 ... -->
*/

Explanation

Here:

  • an XMLSchemata instance is created by loading the given file;
  • its stringify method does the job by:
    • looking up the schema element by the root object key (ExportDebtRequestsResponse)
    • creating a temporary XMLMarshaller
    • invoking its stringify method that actually concatenates the XML string.

Q&A

Is the output guaranteed to be valid?

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.

So what does stringify do exactly?

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.

What does "-ta" mean in "schemata"?

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.

What if the root element local name is present in multiple namespaces?

It's always possible to create an XMLMarshaller explicitly, using the necessary namespace URI.

XMLSchemata's stringify is only a top level wrapper.

What if the schema definition is split by multiple sources?

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.

Clone this wiki locally