简体   繁体   English

根据NodeJS中的模式(xsd)验证XML

[英]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? NPM中的任何XML库是否支持针对XSD架构验证XML?

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. 注意: xsd包不是它看起来的那样,并且node-xerces被破坏/为空。

Hij1nx (Paolo Fragomeni) pointed me at https://github.com/polotek/libxmljs Hij1nx(Paolo Fragomeni)在https://github.com/polotek/libxmljs上指出了我

After half an hour of trying to figure out the API, I have a solution: 在尝试找出API后半小时,我有一个解决方案:

#!/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. 我不知道这是否适用于通过URI引用其他模式的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM