⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 domsample.java

📁 java2 primer plus一书源程序
💻 JAVA
字号:
import javax.xml.parsers.DocumentBuilder; 
import javax.xml.parsers.DocumentBuilderFactory;  
import javax.xml.parsers.FactoryConfigurationError;  
import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;  
import org.xml.sax.SAXParseException;

import java.io.FileInputStream;
import java.io.File;
import java.io.IOException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.DOMException;

public class DOMSample
{
    public static void main( String[] args )
    {
        try
        {
            File file = new File( "book.xml" );
            if( !file.exists() )
            {
                System.out.println( "Couldn't find file..." );
                return;
            }

	    // Parse the document
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse( file );

            // Walk the document
            Element root = document.getDocumentElement();
            System.out.println( "root=" + root.getTagName() );

            // List the children of <books>; a set of <book> elements
            NodeList list = root.getChildNodes();
            for( int i=0; i<list.getLength(); i++ )
            {
                Node node = list.item( i );
                if( node.getNodeType() == node.ELEMENT_NODE )
                {
		    // Found a <book> element
		    System.out.println( "Handling node: " + node.getNodeName() );
		    Element element = ( Element )node;
		    System.out.println( "\tCategory Attribute: " + element.getAttribute( "category" ) );
                    
		    // Get its children: <author>, <title>, <price>
		    NodeList childList = element.getChildNodes();
                    for( int j=0; j<childList.getLength(); j++ )
                    {
			// Once we have one of these nodes we need to find its
			// text element
                        Node childNode = childList.item( j );
			if( childNode.getNodeType() == childNode.ELEMENT_NODE )
			{
			    NodeList childNodeList = childNode.getChildNodes();
			    for( int k=0; k<childNodeList.getLength(); k++ )
			    {
				Node innerChildNode = childNodeList.item( k );
				System.out.println( "\t\tNode=" + innerChildNode.getNodeValue() ); 
			    }
			}
                    }
                }
            }
        } catch( Exception e )
        {
            e.printStackTrace();
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -