import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
/**
* domdemo uses jaxp to acquire a documentbuilder to build a dom document from an xml file.
* the example xml file represents a shopping cart.
*
* the following jars must be in your classpath:
* - jaxp.jar
* - xerces.jar (for sax parser and dom object implementations)
*
* download jaxp (which includes these jars) here: http://java.sun.com/xml/
* find additional xerces info here: http://xml.apache.org/
*
**/
public class domdemo
{
public static void main( string[] args )
{
try
{
documentbuilderfactory factory = documentbuilderfactory.newinstance();
system.out.println( "documentbuilderfactory classname: " + factory.getclass().getname() );
documentbuilder builder = factory.newdocumentbuilder();
system.out.println( "documentbuilder classname: " + builder.getclass().getname() );
//parse the xml file and create the document
document document = builder.parse( "cart.xml" );
/*
at this point, all data in the xml file has been parsed and loaded into memory
in the form of a dom document object. the document is a tree of node objects.
this printnode() method simply recurses through a node tree and displays info
about each node.**/
printnode( document, "" );
}
catch( exception e )
{
e.printstacktrace();
}
}
/**
* printnode is a recursive method that prints info about each node
* in a node tree to system.out. call it with the root node of your node tree and
* an initial indent of ""
**/
public static void printnode( node node, string indent )
{
string text = null;
if( node.getnodetype() == node.text_node )
text = node.getnodevalue().trim();
else
text = node.getnodename();
if( text.length() > 0 )
system.out.println( indent + getnodetypename( node ) + ": " + text );
nodelist childnodes = node.getchildnodes();
for( int i = 0; i < childnodes.getlength(); i++ )
printnode( childnodes.item( i ), indent + " " );
}
/**
* getnodetypename returns a string containing the type-name of the specified node.
**/
public static string getnodetypename( node node )
{
switch( node.getnodetype() )
{
case node.text_node:
return "text";
case node.element_node:
return "element";
case node.attribute_node:
return "attribute";
case node.entity_node:
return "entity";
case node.document_node:
return "document";
case node.cdata_section_node:
return "cdata_section";
case node.comment_node:
return "comment";
case node.notation_node:
return "notation";
case node.processing_instruction_node:
return "processing instruction";
case node.document_fragment_node:
return "document fragment";
case node.entity_reference_node:
return "entity reference";
}
return "unknown node type";
}
}
闽公网安备 35060202000074号