Validating XML against a schema (xsd) in NodeJS
Asked Answered
N

2

22

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.

Nihilism answered 13/2, 2013 at 15:12 Comment(1)
possible duplicate of Validate XML Syntax / Structure with node.jsGallfly
N
34

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.

Nihilism answered 14/2, 2013 at 9:30 Comment(2)
I've found this discussion regarding schemas with imports: github.com/libxmljs/libxmljs/issues/202Lidda
Do you have any insight on how to do it without external libraries?Sufficient
E
0

I managed to get it working by using exec calling the xmllint command. I also echoed a variable into ${xml}, and was able to validate with multi file xsd.

exec(
  `echo '${xml}' | xmllint  --schema  ./xml/xsd.xsd /dev/stdin`,
  (error, stdout, stderr) => {
    return res.json({ error, stdout, stderr });
  }
);
Eddi answered 11/8, 2023 at 23:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.