简体   繁体   English

Javascript-DomParser-如何确定非XML字符串

[英]Javascript - DomParser - how to determine non XML string

Here is something I need to do: 这是我需要做的事情:

  1. Parse any given string, make sure it is in XML format. 解析任何给定的字符串,确保其为XML格式。
  2. Count the nodes number if it is XML format. 如果是XML格式,则计算节点数。 And return true. 并返回true。
  3. Return false if the string is non XML. 如果字符串不是XML,则返回false。

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. 我试图使用DOMParser来完成这项工作,但是,无论我将什么字符串提供给DOMParser,它始终将其视为XML,并计数为6个节点。

Here is my script: 这是我的脚本:

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▒>Ӆ▒▒▒ܩ▒b▒b▒▒=▒▒\q▒▒▒▒▒1▒▒▒");
invoke("<music><album>Beethoven</album></music>");

And the following screenshot is the output of my test, and seems it counts the total nodes correctly if the string is XML: 以下屏幕截图是我测试的输出,并且如果字符串是XML,似乎可以正确计数总节点数:

在此处输入图片说明

Could anyone please help. 谁能帮忙。

Cheers, Vincent 干杯,文森特

Check for parsererror in the xmlDoc. 检查xmlDoc中的parsererror

function invoke(msg){
  try{
    var parser = new DOMParser();
    var xmlDoc = parser.parseFromString(msg,"text/xml");
    if( xmlDoc.getElementsByTagName('parsererror').length ) {
      console.log('The string is: ' + msg);
      console.log('Cannot read this string');
      return false;
    } else {
      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;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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