Check for XML errors using JavaScript

27,563

Solution 1

Edit: Here is a more concise example, from MDN:

var xmlString = '<a id="a"><b id="b">hey!</b></a>';
var domParser = new DOMParser();
var dom = domParser.parseFromString(xmlString, 'text/xml');

// print the name of the root element or error message
dump(dom.documentElement.nodeName == 'parsererror' ? 'error while parsing' : dom.documentElement.nodeName);

Solution 2

NoBugs answer above did not work with a current chrome for me. I suggest:

var sMyString = "<a id=\"a\"><b id=\"b\">hey!<\/b><\/a>";
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(sMyString, "text/xml");
dump(oDOM.getElementsByTagName('parsererror').length ? 
     (new XMLSerializer()).serializeToString(oDOM) : "all good"    
);

Solution 3

Just F12 to enter developer mode and check the source there you can then search validateXML and you are to locate a very long complete XML checker for your reference.

I am using react and stuff using the DOMParser to present the error message as:

  handleXmlCheck = () => {
    const { fileContent } = this.state;
    const parser = new window.DOMParser();
    const theDom = parser.parseFromString(fileContent, 'application/xml');
    if (theDom.getElementsByTagName('parsererror').length > 0) {
      showErrorMessage(theDom.getElementsByTagName('parsererror')[0].getElementsByTagName('div')[0].innerHTML);
    } else {
      showSuccessMessage('Valid Xml');
    }
  }

Solution 4

You can also use the package fast-xml-parser, this package have a validate check for xml files:

import { validate, parse } from 'fast-xml-parser';

if( validate(xmlData) === true) {
  var jsonObj = parse(xmlData,options);
}

Solution 5

Basic xml validator in javscript. This code may not valid for advance xml but basic xml.

function xmlValidator(xml){
    // var xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
    while(xml.indexOf('<') != -1){
        var sub = xml.substring(xml.indexOf('<'), xml.indexOf('>')+1);
        var value = xml.substring(xml.indexOf('<')+1, xml.indexOf('>'));
        var endTag = '</'+value+'>';
        if(xml.indexOf(endTag) != -1){
            // console.log('xml is valid');
            // break;
        }else{
            console.log('xml is in invalid');
            break;
        }
        xml = xml.replace(sub, '');
        xml = xml.replace(endTag, '');
        console.log(xml);
        console.log(sub+' '+value+' '+endTag);
    }
}
var xml = "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>";
xmlValidator(xml);
Share:
27,563
caleb531
Author by

caleb531

Hi, I'm Caleb Evans. Here's a little about me: Who I am: a college student from Carlsbad, California What I love: my Lord Jesus Christ, programming, spending time with family, eating pizza What I do: create HTML5 web applications, build useful tools Favorite operating system: OS X Favorite editor: Atom Favorite language: Python Spaces or tabs? Depends.

Updated on August 12, 2022

Comments

  • caleb531
    caleb531 over 1 year

    Question: How do I syntax-check my XML in modern browsers (anything but IE)?

    I've seen a page on W3Schools which includes an XML syntax-checker. I don't know how it works, but I'd like to know how I may achieve the same behavior.

    I've already performed many searches on the matter (with no success), and I've tried using the DOM Parser to check if my XML is "well-formed" (also with no success).

    var xml = 'Caleb';
    var parser = new DOMParser();
    var doc = parser.parseFromString(xml, 'text/xml');
    

    I expect the parser to tell me I have an XML syntax error (i.e. an unclosed name tag). However, it always returns an XML DOM object, as if there were no errors at all.

    To summarize, I would like to know how I can automatically check the syntax of an XML document using JavaScript.

    P.S. Is there any way I can validate an XML document against a DTD (using JS, and not IE)?