Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 949
Pugal Avatar asked Jun 15 '12 12:06

Pugal


1 Answers

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);
like image 82
conrad10781 Avatar answered Oct 16 '22 14:10

conrad10781