XML parser for JavaScript [closed]

Disclaimer: I am the author if the open-source Jsonix library which may be suitable for the task.


A couple of years ago I was also looking for a good XML<->JSON parsing/serialization library for JavaScript. I needed to process XML documents conforming to rather complex XML Schemas. In Java, I routinely use JAXB for the task so I was looking for something similar:

Is there a JavaScript API for XML binding – analog to JAXB for Java?

I failed to find such a tool back then.

So I wrote Jsonix which I consider to be a JAXB analog for JavaScript.

You may find Jsonix suitable, if you’re interested in the following features:

  • XML<->JSON conversion is based on a declaraive mapping between XML and JSON structures
  • This mapping can be generated from an XML Schema or written manually
  • Bidirectional – supports parsing as well as serialization (or unmarshalling/marshalling in other terms).
  • Support elements, attributes and also considers namespaces defined in the XML document.
  • Strictly typed.
  • Strictly structured.
  • Support almost all of the XML Schema built-in types (including special types like QName).
  • Works in browsers as well as Node.js, also compatible to RequireJS/AMD (also to amdefine in Node.js)
  • Has extensive documentation.

However, Jsonix may be an overkill, if your XML is rather simple, does not have an XML Schema or if you’re not interested in strict typing or structures. Check your requirements.

Example

Try it in JSFiddle.

You can take a purchase order schema and generate a mapping for it using the following command:

java -jar node_modules/jsonix/lib/jsonix-schema-compiler-full.jar
  -d mappings -p PO purchaseorder.xsd

You’ll get a PO.js file which describes mappings between XML and JavaScript structures. Here’s a snippet from this mapping file to give you an impression:

var PO = {
    name: 'PO',
    typeInfos: [{
        localName: 'PurchaseOrderType',
        propertyInfos: [{
            name: 'shipTo',
            typeInfo: 'PO.USAddress'
        }, {
            name: 'billTo',
            typeInfo: 'PO.USAddress'
        }, {
            name: 'comment'
        }, {
            name: 'orderDate',
            typeInfo: 'Calendar',
            type: 'attribute'
        }, ...]
    }, {
        localName: 'USAddress',
        propertyInfos: [ ... ]
    }, ...],
    elementInfos: [{
        elementName: 'purchaseOrder',
        typeInfo: 'PO.PurchaseOrderType'
    }, ... ]
};

Having this mapping file you can parse the XML:

// First we construct a Jsonix context - a factory for unmarshaller (parser)
// and marshaller (serializer)
var context = new Jsonix.Context([PO]);

// Then we create a unmarshaller
var unmarshaller = context.createUnmarshaller();

// Unmarshal an object from the XML retrieved from the URL
unmarshaller.unmarshalURL('po.xml',
    // This callback function will be provided
    // with the result of the unmarshalling
    function (unmarshalled) {
        // Alice Smith
        console.log(unmarshalled.value.shipTo.name);
        // Baby Monitor
        console.log(unmarshalled.value.items.item[1].productName);
    });

Or serialize your JavaScript object as XML:

// Create a marshaller
var marshaller = context.createMarshaller();

// Marshal a JavaScript Object as XML (DOM Document)
var doc = marshaller.marshalDocument({
    name: {
        localPart: "purchaseOrder"
    },
    value: {
        orderDate: { year: 1999, month: 10, day: 20 },
        shipTo: {
            country: "US",
            name: "Alice Smith",
            street: "123 Maple Street",
            city: "Mill Valley",
            state: "CA",
            zip: 90952
        },
        billTo: { /* ... */ },
        comment: 'Hurry, my lawn is going wild!',
        items: { /* ... */ }
    }
});

You can try it in JSFiddle to see how it works in practice.


Additional disclaimer: this answer is high-voted because of the following discussion on meta. So please be aware of the “meta-effect”. High votes here do not necessarily mean that Jsonix is good, applicable or recommended by the community. Do not be mislead by the high votes.

Leave a Comment