Validate xml/json before decoding in nodejs

I was trying to get the response from some server. Server can send response in xml/json format based on the request type.

Now how I can determine if the data has come in xml/json format, if the data is in xml format, then I can convert xml to json and do processing on json.

Inside try/catch will not help for me, as I get the data json either stringified/parsified format.

Now what is the best way to achieve this? Is there ant way to determine if the data is xml/json format before decoding?

Regards, -M-

Maybe just a quick string search if it has the proper XML format or not?

if (request.indexOf("<?xml") != -1) {
   parse xml object...
}
else {
   parse json object...
}

I mean after all it is just received as a string and should be formatted accordingly if its XML or json json starting like "{" and XML should be starting like "

I know this is an older post, but I came across it, and unfortunately, Patrick's answer wasn't terribly helpful for me. At best, you may determine that the string was at least attempting to be XML, at worse, you won't even get a match because it may have been prefixed with a space, etc. Also not a great situation, is finding out the XML itself is still not valid because of a missing tag, etc, which seemed to be the whole point of the OP.

I've found libxmljs to be the best solution for what you're looking for. You can parse, validate the basic string, as well as a detailed structure.

An example of checking for an XML syntax would be with something like:

program.isValidSyntaxStructure = function (text) {
    try {
        libxmljs.parseXml(text);
    } catch (e) {
        return false;
    }

    return true;
};

An example of checking for a specific structure/schema would be with something like:

var xsd = '<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"><xs:element name="comment" type="xs:string"/></xs:schema>';
var xml_valid = '<?xml version="1.0"?><comment>A comment</comment>';
var xml_invalid = '<?xml version="1.0"?><commentt>A comment</commentt>';

var xsdDoc = libxml.parseXml(xsd);
var xmlDocValid = libxml.parseXml(xml_valid);
var xmlDocInvalid = libxml.parseXml(xml_invalid);

assert.equal(xmlDocValid.validate(xsdDoc), true);
assert.equal(xmlDocInvalid.validate(xsdDoc), false);