How to check the string is xml or not using Node.js

Viewed 415

I need some help. I am checking the input string is json/xml using Node.js. I am explaining my code which gives the output to check the given string is json or not.

isJSON = (str) => { 
    try { 
        return (JSON.parse(str) && !!str); 
    } catch (e) { 
        return false; 
    }
} 

const result= isJSON(string);       

So here I am able to check whether the string i.e string is JSON or not. In similar way I need to check for XML content.

Lets say I have the string which is given below:

const string = '<config xmlns="http://tail-f.com/ns/config/1.0">
   <devices xmlns="http://tail-f.com/ns/ncs">
      <global-settings>
         <read-timeout>120</read-timeout>

     </global-settings>
</devices>
</config>';

So I need to check the above content is XML content or not using node.js. Can anybody help me to resolve this?

1 Answers

In XML the first character will always be "<". In JSON, apart from trivial cases, the first non-space character will be "[" or "{". So it's easy to decide between them.

After that, to decide whether it's well-formed XML or well-formed JSON, you need to put it through a parser.

(Incidentally, we haven't found an XML parser on node.js that has a really high level of conformance in terms of handling edge cases. But there are plenty that are good enough for practical purposes.)

Related