You can get access to an element's attributes with the element's attributes property. You can get attribute names and values with the name and value properties of attribute objects, and I used the value property earlier in this chapter. It's also worth noting that because attributes are themselves nodes, you can use the nodeName and nodeValue properties to do the same thing; I'll do that in this example to show how it works. Here's how I augment the previous example in our final parsing example in this chapter, looping over all the attributes an element has and listing them (note that you could use the name and value properties here instead of nodeName and nodeValue ): Listing ch07_08.html<HTML> <HEAD> <TITLE> Parsing XML to read attributes </TITLE> <XML ID="meetingsXML" SRC="ch07_01.xml"></XML> <SCRIPT LANGUAGE="JavaScript"> function parseDocument() { documentXML = document.all("meetingsXML").XMLDocument resultsDIV.innerHTML = iterateChildren(documentXML, "") } function iterateChildren(theNode, indentSpacing) { var typeData switch (theNode.nodeType) { case 1: typeData = "element" break case 2: typeData = "attribute" break case 3: typeData = "text" break case 4: typeData = "CDATA section" break case 5: typeData = "entity reference" break case 6: typeData = "entity" break case 7: typeData = "processing instruction" break case 8: typeData = "comment" break case 9: typeData = "document" break case 10: typeData = "document type" break case 11: typeData = "document fragment" break case 12: typeData = "notation" } var text if (theNode.nodeValue != null) { text = indentSpacing + theNode.nodeName + " = " + theNode.nodeValue + " (Node type: " + typeData + ")" } else { text = indentSpacing + theNode.nodeName + " (Node type: " + typeData + ")" } if (theNode.attributes != null) { if (theNode.attributes.length > 0) { for (var loopIndex = 0; loopIndex < theNode.attributes.length; loopIndex++) { text += " (Attribute: " + theNode.attributes(loopIndex).nodeName + " = \"" + theNode.attributes(loopIndex).nodeValue + "\")" } } } text += "<BR>" if (theNode.childNodes.length > 0) { for (var loopIndex = 0; loopIndex < theNode.childNodes.length; loopIndex++) { text += iterateChildren(theNode.childNodes (loopIndex), indentSpacing + " ") } } return text } </SCRIPT> </HEAD> <BODY> <CENTER> <H1> Parsing XML to read attributes </H1> </CENTER> <CENTER> <INPUT TYPE="BUTTON" VALUE="Parse and display the document" ONCLICK="parseDocument()"> </CENTER> <DIV ID="resultsDIV"></DIV> </BODY> </HTML> You can see the results of this page in Figure 7-6. As you can see, both elements and attributes are listed in that figure. Figure 7-6. Listing elements and attributes in Internet Explorer.
|