Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML parser for JavaScript [closed]

I am looking for a good JavaScript library for parsing XML data. It should be much easier to use than the built-in XML DOM parsers bundled with the browsers.

I got spoiled a bit working with JSON and am looking forward to something on similar lines for XML.

like image 822
Gulzar Nazim Avatar asked Sep 17 '08 13:09

Gulzar Nazim


People also ask

Can you parse XML in JavaScript?

In a JavaScript action you can parse and generate XML using the xml-js library. The first example parses XML content of a local variable into a JavaScript object structure. You can also retrieve XML content from another source, like a process variable or an external web service.

Can browser parse XML?

All major browsers have a built-in XML parser to access and manipulate XML.

Can you use an XML parser for HTML?

You can try parsing an HTML file using a XML parser, but it's likely to fail. The reason is that HTML documents can have the following HTML features that XML parsers don't understand. XML parsers will fail to parse any HTML document that uses any of those features.


4 Answers

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.

like image 61
lexicore Avatar answered Oct 14 '22 07:10

lexicore


I use jQuery for this. Here is a good example:

(EDIT: Note - the following blog seems to have gone away.)

http://blog.reindel.com/2007/09/24/jquery-and-xml-revisited/

There are also lots and lots of good examples in the jQuery documentation:

http://www.webmonkey.com/tutorial/Easy_XML_Consumption_using_jQuery?oldid=20032

EDIT: Due to the blog for my primary example going away, I wanted to add another example that shows the basics and helps with namespace issues:

http://www.zachleat.com/web/selecting-xml-with-javascript/

like image 32
shadit Avatar answered Oct 14 '22 06:10

shadit


If your XML is in a simple format you may look at jQuery and the XML to JSON plugin or the xmlObjectifier.

For a straight parser you may want to look at XML for <SCRIPT>.

like image 2
palehorse Avatar answered Oct 14 '22 06:10

palehorse


Have you tried XML for SCRIPT. I have to admit, that I have never used it personally, but I have heard/read a few good things about it.

Give it a try and maybe share your experience here?

like image 1
Mo. Avatar answered Oct 14 '22 05:10

Mo.