Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating XML against a schema (xsd) in NodeJS

Do any of the XML libraries in NPM support the validation of XML against an XSD schema?

I would look myself, but:

$ npm search xml 2>/dev/null | wc -l
212

Note: the xsd package is not what it seems and node-xerces is broken/empty.

like image 230
fadedbee Avatar asked Feb 13 '13 15:02

fadedbee


People also ask

How you will validate XML document using schema?

XML documents are validated by the Create method of the XmlReader class. To validate an XML document, construct an XmlReaderSettings object that contains an XML schema definition language (XSD) schema with which to validate the XML document. The System. Xml.

How do you validate against XSD?

Simply go to the XML Tools > Validate Now option and click on it. You can also press Ctrl + Alt + Shift + M key combination to open Validate Now option. Now, select the XSD file against which you want to validate the opened XML document. Simply browse and then import the XSD file in the respective field.

Can we validate XML documents against a schema?

You can validate your XML documents against XML schemas only; validation against DTDs is not supported. However, although you cannot validate against DTDs, you can insert documents that contain a DOCTYPE or that refer to DTDs.


1 Answers

Hij1nx (Paolo Fragomeni) pointed me at https://github.com/polotek/libxmljs

After half an hour of trying to figure out the API, I have a solution:

#!/usr/local/bin/node
var x = require('libxmljs');

var xsd = '<?xml version="1.0" encoding="utf-8" ?><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://example.com/XMLSchema/1.0" targetNamespace="http://example.com/XMLSchema/1.0" elementFormDefault="qualified" attributeFormDefault="unqualified"><xs:element name="foo"></xs:element></xs:schema>'
var xsdDoc = x.parseXmlString(xsd);

var xml0 = '<?xml version="1.0" encoding="UTF-8"?><foo xmlns="http://example.com/XMLSchema/1.0"></foo>';
var xmlDoc0 = x.parseXmlString(xml0);
var xml1 = '<?xml version="1.0" encoding="UTF-8"?><bar xmlns="http://example.com/XMLSchema/1.0"></bar>';
var xmlDoc1 = x.parseXmlString(xml1);

var result0 = xmlDoc0.validate(xsdDoc);
console.log("result0:", result0);

var result1 = xmlDoc1.validate(xsdDoc);
console.log("result1:", result1);

This produces the output:

result0: true
result1: false

I have no idea whether/how this will work with schemas which reference other schemas via URIs.

like image 146
fadedbee Avatar answered Sep 22 '22 14:09

fadedbee