title: Javascript - DomParser - how to determine non XML string
body: <p>Here is something I need to do:</p>
  
  <ol>
  <li>Parse any given string, make sure it is in XML format. </li>
  <li>Count the nodes number if it is XML format. And return true.</li>
  <li>Return false if the string is non XML. </li>
  </ol>
  
  <p>I was trying to use a DOMParser to do the job, however, regardless what string I give it to the DOMParser, it always treat it as XML, and count it has 6 nodes.</p>
  
  <p>Here is my script:</p>
  
  <pre><code>function invoke(msg){
  try{
      var parser = new DOMParser();
      var xmlDoc = parser.parseFromString(msg,"text/xml");
      var nodes = xmlDoc.getElementsByTagName('*')
      console.log('The string is: ' + msg);
      console.log('This string has ' + nodes.length + ' nodes.');
      return true;
   }
  
   catch(err){
       console.log('The string is: ' + msg);
       console.log('Cannot read this string');
       return false;
  }
  }
  
  invoke("hello world");
  invoke("▒0藤▒]Ir▒|̆x▒$۾▒e▒(E▒&gt;Ӆ▒▒▒ܩ▒b▒b▒▒=▒▒\q▒▒▒▒▒1▒▒▒");
  invoke("&lt;music&gt;&lt;album&gt;Beethoven&lt;/album&gt;&lt;/music&gt;");
  </code></pre>
  
  <p>And the following screenshot is the output of my test, and seems it counts the total nodes correctly if the string is XML:</p>
  
  <p><a href="https://i.stack.imgur.com/SicGl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SicGl.png" alt="enter image description here"></a></p>
  
  <p>Could anyone please help.</p>
  
  <p>Cheers,
  Vincent</p>