![](/img/trans.png)
[英]How do you get only XML elements and not whitespace with the javascript DOMParser?
[英]Javascript - DomParser - how to determine non XML string
這是我需要做的事情:
我試圖使用DOMParser來完成這項工作,但是,無論我將什么字符串提供給DOMParser,它始終將其視為XML,並計數為6個節點。
這是我的腳本:
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>");
以下屏幕截圖是我測試的輸出,並且如果字符串是XML,似乎可以正確計數總節點數:
誰能幫忙。
干杯,文森特
檢查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.