---
title: " JAVA操作XML的完整例子——W3C DOM篇"
author: "daniel_kwok"
date: "2008-10-15T01:00:52Z"
tags: []
slug: "java-xml-w3c-dom"
draft: false
lastmod: "2008-10-15T01:00:52Z"
id: 252930
url: "https://dkstudio.iteye.com/blog/252930"
---

这是一个用JAVA W3C DOM 进行XML操作的例子，包含了查询、增加、修改、删除、保存的基本操作。较完整的描述了一个XML的整个操作流程。适合刚入门JAVA XML操作的朋友参考和学习。

假设有XML文件：test1.xml

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;?xml version="1.0" encoding="UTF-8"?&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;books&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;book&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;name&gt;哈里波特&lt;/name&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;price&gt;10&lt;/price&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;memo&gt;这是一本很好看的书。&lt;/memo&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;/book&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;book id="B02"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;name&gt;三国演义&lt;/name&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;price&gt;10&lt;/price&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;memo&gt;四大名著之一。&lt;/memo&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;/book&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;book id="B03"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;name&gt;水浒&lt;/name&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;price&gt;6&lt;/price&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;memo&gt;四大名著之一。&lt;/memo&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;/book&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;book id="B04"&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;name&gt;红楼&lt;/name&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;price&gt;5&lt;/price&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  &lt;memo&gt;四大名著之一。&lt;/memo&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif) &lt;/book&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)&lt;/books&gt;    
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)

 

下面是为Test.java

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import java.io.File;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import java.io.FileNotFoundException;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import java.io.FileOutputStream;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import java.io.IOException;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import org.w3c.dom.\*;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import org.xml.sax.SAXException;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import javax.xml.parsers.\*;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import javax.xml.transform.\*;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import javax.xml.transform.dom.DOMSource;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import javax.xml.transform.stream.\*;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)import javax.xml.xpath.\*;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedBlock.gif)public class Test ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static void main(String\[] args) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        Element theBook=null, theElem=null, root=null;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        try ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            factory.setIgnoringElementContentWhitespace(true);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)              
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            DocumentBuilder db=factory.newDocumentBuilder();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            Document xmldoc=db.parse(new File("Test1.xml"));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            root=xmldoc.getDocumentElement();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)              
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  新建一本书开始 ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook=xmldoc.createElement("book");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theElem=xmldoc.createElement("name");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theElem.setTextContent("新书");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook.appendChild(theElem);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)              
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theElem=xmldoc.createElement("price");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theElem.setTextContent("20");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook.appendChild(theElem);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theElem=xmldoc.createElement("memo");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theElem.setTextContent("新书的更好看。");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook.appendChild(theElem);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            root.appendChild(theBook);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  新建一本书开始 ----");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(xmldoc);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  新建一本书完成 ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  下面对《哈里波特》做一些修改。 ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  查询找《哈里波特》----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook=(Element) selectSingleNode("/books/book\[name='哈里波特']", root);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  查询找《哈里波特》 ----");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(theBook);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  此时修改这本书的价格 -----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName返回的是NodeList，所以要跟上item(0)。另外，getElementsByTagName("price")相当于xpath的".//price"。  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  此时修改这本书的价格 ----");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(theBook);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  另外还想加一个属性id，值为B01 ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook.setAttribute("id", "B01");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  另外还想加一个属性id，值为B01 ----");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(theBook);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  对《哈里波特》修改完成。 ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  要用id属性删除《三国演义》这本书  ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook=(Element) selectSingleNode("/books/book\[@id='B02']", root);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  要用id属性删除《三国演义》这本书 ----");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(theBook);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            theBook.getParentNode().removeChild(theBook);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  删除后的ＸＭＬ ----");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(xmldoc);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            //---  再将所有价格低于10的书删除  ----  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            NodeList someBooks=selectNodes("/books/book\[price&lt;10]", root);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  再将所有价格低于10的书删除  ---");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            System.out.println("---  符合条件的书有　"+someBooks.getLength()+"本。  ---");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)            for(int i=0;i&lt;someBooks.getLength();i++) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                someBooks.item(i).getParentNode().removeChild(someBooks.item(i));  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)            }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            output(xmldoc);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            saveXml("Test1\_Edited.xml", xmldoc);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (ParserConfigurationException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (SAXException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (IOException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static void output(Node node) ...{//将node的XML字符串输出到控制台  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        TransformerFactory transFactory=TransformerFactory.newInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        try ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            Transformer transformer = transFactory.newTransformer();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            transformer.setOutputProperty("encoding", "gb2312");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            transformer.setOutputProperty("indent", "yes");  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            DOMSource source=new DOMSource();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            source.setNode(node);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            StreamResult result=new StreamResult();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            result.setOutputStream(System.out);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)              
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            transformer.transform(source, result);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (TransformerConfigurationException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (TransformerException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }     
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static Node selectSingleNode(String express, Object source) ...{//查找节点，并返回第一个符合条件节点  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        Node result=null;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        XPathFactory xpathFactory=XPathFactory.newInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        XPath xpath=xpathFactory.newXPath();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        try ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (XPathExpressionException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)          
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return result;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static NodeList selectNodes(String express, Object source) ...{//查找节点，返回符合条件的节点集。  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        NodeList result=null;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        XPathFactory xpathFactory=XPathFactory.newInstance();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        XPath xpath=xpathFactory.newXPath();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        try ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)        } catch (XPathExpressionException e) ...{  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            e.printStackTrace();  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)          
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return result;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ContractedSubBlock.gif)    public static void saveXml(String fileName, Document doc) ...{&lt;/sp&gt;