2

I have a string that may or may not contain valid xml content. How can I test to see if that particular string is a valid xml document or not? I would prefer this to be in jQuery or just plain javascript.

thanks.

Niner
  • 2,074
  • 6
  • 37
  • 47
  • possible duplicate of [Regex to check for XML if it is well formed](http://stackoverflow.com/questions/1752492/regex-to-check-for-xml-if-it-is-well-formed) – attila Mar 13 '14 at 00:09

1 Answers1

9

You can try this JQuery code:

function isXML(xml){
    try {
        xmlDoc = $.parseXML(xml); //is valid XML
        return true;
    } catch (err) {
        // was not XML
        return false;
    }
}
adearriba
  • 493
  • 2
  • 6
  • 1
    This always returns false because of 'ReferenceError: xmlDoc is not defined'. declaring "var xmlDoc = $.parseXML(xml)" works fine. – Laura Vieira Jun 19 '18 at 17:44