I want to validate XML for the below using node.js. Can anyone suggest good node.js module that works both on windows/linux?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With