简体   繁体   中英

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

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 ie 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?

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM