Validating XML against a schema (xsd) in NodeJS

后端 未结 1 1653
眼角桃花
眼角桃花 2021-02-02 15:59

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         


        
1条回答
  •  太阳男子
    2021-02-02 16:17

    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 = ''
    var xsdDoc = x.parseXmlString(xsd);
    
    var xml0 = '';
    var xmlDoc0 = x.parseXmlString(xml0);
    var xml1 = '';
    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.

    0 讨论(0)
提交回复
热议问题