📄 domsample2.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;
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 + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -