XML DOM Browser Differences

Different browsers handle empty text nodes in XML DOM differently.

Example

The following example uses an XML file books.xml.

Function loadXMLDoc(), located in external JavaScript, used to load XML files.

Display the length of the node list
This example displays the length of a node list. The result is different in IE and other browsers.
Ignore empty text between nodes
This example checks the nodeType of the node and only handles element nodes.

Browser Differences in DOM Parsing

All modern browsers support the W3C DOM specification.

However, there are differences between browsers. The important differences are two:

  • Ways to load XML
  • Ways to handle whitespace and newlines

In \Parsing XML DOM"This section has explained different ways to load XML."

In this section, we will explain different ways to handle whitespace and newlines.

DOM - Whitespace and Newlines

XML often contains newline or whitespace characters between nodes. This is a common situation when using simple editors (such as Notepad).

The following example (edited by Notepad) contains CR/LF between lines and two spaces before each sub-node:

<book>
  <title>Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

Firefox and some other browsers treat empty whitespace or line breaks as text nodes, while Internet Explorer does not.

The following code snippet shows how many child nodes the root element (of books.xml) has:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement.childNodes;
document.write("Number of child nodes: " + x.length);

Example explanation:

  • By using loadXMLDoc() Put "books.xml"Load xmlDoc with"
  • Get the child nodes of the root element
  • Output the number of child nodes

The result depends on the browser used. Firefox outputs 9, while IE outputs 4.

TIY

Ignore empty text between nodes

To ignore the empty text nodes between element nodes, you need to check the node type. The type of element node is 1:

xmlDoc=loadXMLDoc("books.xml");
x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{ 
if (x[i].nodeType==1)
  {// only process element nodes 
  document.write(x[i].nodeName);
  document.write("<br />");
  } 
}

Example explanation:

  • By using loadXMLDoc() Put "books.xml"Load xmlDoc with"
  • Get the child nodes of the root element
  • Check the node type of each child node. If the node type is "1", it is an element node

TIY (simple) Or TIY (complete)