P2.java

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

/**
Simple demonstration of DOM.
Reads XML version of "Midsummer Night's Dream", prints all Act and 
Scene titles and stage directions, with indentation indicating the
nesting of the XML document.  Ignores parsing errors.
*/
public class P2
{
    public static void main(String[] argv)
    {
        DocumentBuilderFactory f = 
            DocumentBuilderFactory.newInstance();
        try {
            DocumentBuilder b = f.newDocumentBuilder();
            Document doc = b.parse(new File("dream.xml"));
            showTitles(doc.getDocumentElement(),"");
            }
        catch (Exception e) {
            e.printStackTrace();
            }
    }

    /**
    Display all TITLE and STAGEDIR elements in the tree rooted at 'e'.
    */
    private static void showTitles(Element e,String indent)
    {
        NodeList kids = e.getChildNodes();
        for (int i=0; i<kids.getLength(); i++) {
            if (kids.item(i) instanceof Element) {
                Element e2 = (Element)(kids.item(i));
                if (e2.getTagName().equals("STAGEDIR") ||
                        e2.getTagName().equals("TITLE")) {
                    Text textNode = (Text)(e2.getFirstChild());

                    if (e2.getTagName().equals("TITLE"))
                        System.out.println();

                    String data = textNode.getData();
                    // Remove extraneous line breaks, etc.
                    data = data.trim().replaceAll("\\s+"," ");
                    System.out.println(indent+data);
                    }

                showTitles(e2,indent+"   ");
                }
            }
    }
}