Mega Code Archive

 
Categories / Java / XML
 

Getting Attributes with DOM

import java.io.IOException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.sun.org.apache.xerces.internal.parsers.DOMParser; public class MainClass {   public static void main(String args[]) throws IOException, SAXException {     DOMParser parser = new DOMParser();     parser.parse("games.xml");     Document dom = parser.getDocument();     NodeList games = dom.getElementsByTagName("game");     for (int i = 0; i < games.getLength(); i++) {       Node aNode = games.item(i);       System.out.println(aNode.getFirstChild().getNodeValue());       NamedNodeMap attributes = aNode.getAttributes();       for (int a = 0; a < attributes.getLength(); a++) {         Node theAttribute = attributes.item(a);         System.out.println(theAttribute.getNodeName() + "=" + theAttribute.getNodeValue());       }     }   } }