DOMParser.parseFromString(text,“text/html”) only i

2019-07-24 12:21发布

问题:

I have Win 7, 64 Bit, Firefox 32.0.1, Noscript running.

The following code only returns 199 nodes with aXML.getElementsByTagName("node"), whereas there are 300 in the parsed text, which is not well formed xml.

var atext = '';
for (var i=0;i<300;i++) {
    atext += '  <node id="'+i+'" lat="42.5168939" lon="1.553855" version="2" changeset="21730124"/>'+"\n\r";
}
parser = new DOMParser();
aXML= parser.parseFromString(atext , "text/html");
console.log(" nodes: " + aXML.getElementsByTagName("node").length
        +"\n\r atext.length:" + atext.length);
console.log(aXML.getElementsByTagName('node'));

The console shows:

" nodes: 199

 atext.length:25390"
HTMLCollection [ <node#0>, <node#1>, <node#2>, <node#3>, <node#4>, <node#5>, <node#6>, <node#7>, <node#8>, <node#9>, 189 weitere… ]

Could this be a bug?

The web-console doesn't show any error from parseFromString.

(I get a log of other errors lately, that I can't put in any relation to the open tabs.

A promise chain failed to handle a rejection.
Date: Sat Mar 14 2015 22:01:10 GMT+0100
Full Message: null

Could that be related?)

回答1:

The problem is that you are trying to parse XML as HTML. The two are quite different in terms of valid syntax. Instead of using:

aXML= parser.parseFromString(atext , "text/html");

You need to instead use:

aXML= parser.parseFromString(atext , "text/xml");

Also, make sure the XML is valid or it will not parse. In your example, it is not, but I assume that is just a test case.