domsample2.java

来自「java2 primer plus一书源程序」· Java 代码 · 共 70 行

JAVA
70
字号

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;
import org.w3c.dom.Text;

public class DOMSample2
{
    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 );

            // Get the root of the document 
            Element root = document.getDocumentElement();

	    // Build a new book 
	    Element newAuthor = document.createElement( "author" );
	    Text authorText = document.createTextNode( "Tim Lahaye" );
	    newAuthor.appendChild( authorText );
	    Element newTitle = document.createElement( "title" );
	    Text titleText = document.createTextNode( "Desecration" );
	    newTitle.appendChild( titleText );
	    Element newPrice = document.createElement( "price" );
	    Text priceText = document.createTextNode( "19.95" );
	    newPrice.appendChild( priceText );
	    Element newBook = document.createElement( "book" );
	    newBook.setAttribute( "category", "fiction" );
	    newBook.appendChild( newAuthor );
	    newBook.appendChild( newTitle );
	    newBook.appendChild( newPrice );

	    // Add the book to the root
	    root.appendChild( newBook );

	    // Display the document
	    System.out.println( root );
        } catch( Exception e )
        {
            e.printStackTrace();
        }
    }
}

⌨️ 快捷键说明

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