📄 domdemo.java
字号:
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";
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -