[英]Javascript - DomParser - how to determine non XML string
Here is something I need to do: 这是我需要做的事情:
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.