From : http://kickjava.com/2515.htm
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
File f; // The file to parse. Assume this is initialized elsewhere
// Create a factory object for creating DOM parsers
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance ( ) ;
// Now use the factory to create a DOM parser ( a.k.a. a DocumentBuilder )
DocumentBuilder parser = factory.newDocumentBuilder ( ) ;
// Parse the file and build a Document tree to represent its content
Document document = parser.parse ( f ) ;
// Ask the document for a list of all < sect1 > tags it contains
NodeList sections = document.getElementsByTagName ( "sect1" ) ;
// Loop through those < sect1 > elements one at a time, and extract the
// content of their < h3 > tags.
int numSections = sections.getLength ( ) ;
for ( int i = 0; i < numSections; i++ ) {
Element section = ( Element ) sections.item ( i ) ; // A < sect1 >
// Find the first element child of this section ( a < h3 > element )
// and print the text it contains.
Node title = section.getFirstChild ( ) ;
while ( title != null && title.getNodeType ( ) != Node.ELEMENT_NODE )
title = title.getNextSibling ( ) ;
// Print the text contained in the Text node child of this element
if ( title!=null ) System.out.println ( title.getFirstChild ( ) .getNodeValue ( ) ) ;
}
No comments:
Post a Comment