XML parsing

Is there a way to iterate over the immediate children of an XML node in JavaScript without using jquery or a similar library? I tried using ".childNodes", but for some reason it is not working properly. ".childNodes.length" returns a number that is usually greater than the number of immediate nodes, and all tag names (using .tagName) are undefined for some reason. I know that my XML data is generated correctly, because if I call .getElementsByTagName () using the immediate children tags, it works as it should. Some examples of my dilemma:

var root = xmlData.getElementsByTagName("library_geometries")[0]; for (i = 0; i < root.childNodes.length; i++) //get all the geometries { geom = root.childNodes[i]; alert(geom.tagName); } ------------------------------------------------------ geom = root.getElementsByTagName("geometry"); for (i = 0; i < geom.length; i++) //get all the geometries { alert(geom[i].tagName); } 

The first does not work at all, the second works in this example.

+2
source share
3 answers

This is actually an explanation of Hemlock’s answer. I put it here, and not commenting on his answer, because I do not have a place to attract ASCII art in the comments.

Let's say we have the following XML:

 <a><b></b><c></c></a> 

This creates the following DOM:

 <a>--. | <b> | <c> 

which is usually what you expect.

Let's say we now have the following XML:

 <a> <b></b> <c></c> </a> 

You would think that this creates the same DOM. But, according to the standard, you are mistaken. Instead, the standard requires it to generate the following DOM:

 <a>--. | "\n " | <b> | "\n " | <c> | "\n" 

Yes, the spec says that all of these spaces should be written to the DOM. Almost all XML implementations there do this (not only in browsers). The only exception is IE (and the extension of the XML engine in JScript), because Microsoft did not really care about breaking the standards.

Personally, it is useless 99.999% of the time. The only time this would be useful is if you are trying to implement an XML editor. But it’s in the standards, so the browser needs to implement it if they want to meet the standards.

+3
source

You get text nodes (nodeType == 3) mixed with elements. Text nodes probably contain only a space. You just want to filter your loop on nodeType (as Wakey said).

 var root = xmlData.getElementsByTagName("library_geometries")[0]; for (i = 0; i < root.childNodes.length; i++) //get all the geometries { geom = root.childNodes[i]; if (geom.nodeType == 1) { alert(geom.tagName); } } 

https://developer.mozilla.org/en/nodeType

+2
source

Wait for the html document to be parsed. You should run this piece of script when the document is ready, in onload () the document has not yet been parsed, so you may not find the tags.

0
source

Source: https://habr.com/ru/post/1336231/


All Articles