node.jsxmlvalidationxmldomlibxml-js

Node.js - check for well-formed XML


How do you validate check for well-formed xml in node.js? I'm mainly interested in checking only if the file is well formed. Additionally I want to receive a line number where error occurs.

I have the following test xml:

<?xml version="1.0" encoding="UTF-8" ?>
<body>
    <tagname>
        test1
    </tag.name>   <--- error here
    <tagname>
        test2
    </tagname>
</body>

What I have tried so far:

xmldom:

var parser = new DOMParser({errorHandler: (level, error) => {
    console.log (level, error);
}});
var dom = parser.parseFromString(content, 'application/xml');

Problem: There is no indication of error. Error handler is never called, and dom contains "test1" but not "test2". So parser just stops and swallows the error.

libxmljs:

var xmlDoc = libxmljs.parseXml(xml);

Problem: throws not-helpful exception "Premature end of data in tag body".


Solution

  • We had to do some xml-parsing with NodeJS recently as well and ended up using fast-xml-parser and so far we're super happy with it. Applied to your case you can use the .validate(..) method:

    const xmlString = `<?xml version="1.0" encoding="UTF-8" ?>
    <body>
        <tagname>
            test1
        </tag.name>   <--- error here
        <tagname>
            test2
        </tagname>
    </body>`;
    
    const parser = require('fast-xml-parser');
    
    const validationResult = parser.validate(xmlString);
    console.log(validationResult)
    
    // validationResult will be an object of:
    {
      err: {
        code: 'InvalidTag',
        msg: "Closing tag 'tagname' is expected inplace of 'tag.name'.",
        line: 5
      }
    }