Validate XML Syntax / Structure with node.js

I want to validate XML for the below using node.js. Can anyone suggest good node.js module that works both on windows/linux?

  • Validate XML Syntax
  • Validate XML Structure (Schema)

Thanks in advance.

I know this is an older post, but I came across it, and unfortunately, Ankit's answer wasn't terribly helpful for me. It focused at best on whether the input is valid XML syntax, not whether is adhered to a schema, which was part of the OP.

I've found libxmljs to be the best solution for what you're looking for. You can parse, validate the basic string, as well as a detailed structure.

An example of checking for an XML syntax would be with something like:

program.isValidSyntaxStructure = function (text) {
    try {
        libxmljs.parseXml(text);
    } catch (e) {
        return false;
    }

    return true;
};

An example of checking for a specific structure/schema would be with something like:

var xsd = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="comment" type="xs:string"/></xs:schema>';
var xml_valid = '<?xml version="1.0"?><comment>A comment</comment>';
var xml_invalid = '<?xml version="1.0"?><commentt>A comment</commentt>';

var xsdDoc = libxml.parseXml(xsd);
var xmlDocValid = libxml.parseXml(xml_valid);
var xmlDocInvalid = libxml.parseXml(xml_invalid);

assert.equal(xmlDocValid.validate(xsdDoc), true);
assert.equal(xmlDocInvalid.validate(xsdDoc), false);

You may have to do some research on your own, but I trust at least one of the Node.js XML Parser Modules should be able to help.

The native implementations (such as node-expat) do require building of a C++ extension so that may break the requirement for the module to work in both Windows and Linux but because of the speed they provide you should try them out anyway, especially if you are dealing with large XML files.

xmldom should be able to provide some very simple XML parsing from strings. You can then create a function to simply return true/false depending on the output of the parse (check out how DOMParser returns errors).