University of Cincinnati logo and link  
XML Example 
 
  UC ingot
  • Our XML file:
<?xml version="1.0" ?> 

<database>
 <drivername>com.mysql.jdbc.Driver</drivername>
 <databaseURL>jdbc:mysql://localhost/students</databaseURL>
</database>

  • Our tester:
/*
 * TestXML.java
 *
 * Created on May 8, 2003, 4:36 PM
 */

import javax.xml.parsers.*;
import org.w3c.dom.*;
import java.io.*;

/**
 *
 * @author  default
 * @version 
 */
public class TestXML {

    /** Creates new TestXML */
    public TestXML() {
    }
    
    public void runTest() {
        try {
            // First, read in data from XML file.  
            // We'll hardcode the filename now, but change it to an attribute later.
            File f = new File("datasource.xml");
            
            // Get a factory and a builder.  
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            
            // Parse the doucment
            Document doc = builder.parse(f);
            
            // Get the root element.
            Element root = doc.getDocumentElement();   
            
            // Now get the children of the root element.
            NodeList children = root.getChildNodes();
            
            // loop through the elements.
            for (int i=0; i < children.getLength(); i++) {
                
                // Get the child as a node.
                Node child = children.item(i);
                
                // We shouldn't get any output here for our simple XML file, 
                // but just in case...
                if (child instanceof Text) {
                    System.out.println("Text: " + ((Text) child).getData().trim());
                } else if (child instanceof Element) {
                
                    // This is certainly not flexible.  But we know from our XML
                    // that, if this is a child, it will only contain text.  
                    // A better way to do this would be a recursive loop with an 
                    // instanceof test.
                    
                    Text textNode = (Text) child.getFirstChild();
                    System.out.println("TextNode: " + textNode.getData().trim());
                }
                
            }
            
            // Informational.
            System.out.println("Finished loop");
        } catch (Exception e) {
            // Handle errors.
            System.out.println("Exception in runTest.  Message: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    
    public static void main(String args[]) {
        
            // Create a TestXML object and run the test.
          TestXML txml = new TestXML();
          txml.runTest();
    }

}
 

  • The Output:

 Lab