tags:

views:

154

answers:

2

Hi.

I am a total beginner in JS/XML.

I have this simple code that needs to be extended to list on the screen attributes and their values for each element of a XML file.

      function printElement(indent, node) 
      {
         var i;
         if (node.nodeType == 3) 
          {
              document.write("<br />" +indent + node.nodeValue);
          }
         else 
          {  document.write("<br />" +indent + "[" + node.nodeName + "]");
             for (i = 0; i < node.childNodes.length; i++) 
               {
                  printElement(indent+tab, node.childNodes[i]);
               }
             document.write("<br />" +indent + "[/" + node.nodeName + "]");
          }
      }

I think I am supposed to use node.attributes but I don't know exactly how. I don't know attribute's name.

This also doesn't work:

document.write("<br />" +indent + node.attributes[0].nodeValue);

The browser says "Object required" if (node.nodeType == 3). If (node.nodeType == 2) the code lists something but not the attributes.

A: 

Try

node.attributes.getNamedItem("id").nodeValue

Where id is the attribute name.

Or

node.attributes[0].nodeValue
Phil Carter
Hi Phil. For (node.nodeType == 2) the code lists something but not the attributes.
Altar
> Where id is the attribute nameAlso, I don't know the name of the attribute - it can vary.
Altar
+2  A: 

Try this:

for (var i = 0; i < element.attributes.length; i++)
{
   var att = element.attributes[i];
   document.write(att.nodeName) + "=" + att.nodeValue + "<br/>");
}
Robert Rossney