Java操作XML文件大合集(增刪改查)


package wzs;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
public class  XMLWriter{
    public static void main(String[] args) {
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        Element theBook=null, theElem=null, root=null;
        try {
            factory.setIgnoringElementContentWhitespace(true);
            
            DocumentBuilder db=factory.newDocumentBuilder();
            Document xmldoc=db.parse(new File("MyXml.xml"));
            root=xmldoc.getDocumentElement();
            
            //--- 新建一本書開始 ----
            theBook=xmldoc.createElement("book");
            theElem=xmldoc.createElement("name");
            theElem.setTextContent("新書");
            theBook.appendChild(theElem);
            
            theElem=xmldoc.createElement("price");
            theElem.setTextContent("20");
            theBook.appendChild(theElem);
            theElem=xmldoc.createElement("memo");
            theElem.setTextContent("新書的更好看。");
            theBook.appendChild(theElem);
            root.appendChild(theBook);
            System.out.println("--- 新建一本書開始 ----");
            output(xmldoc);
            //--- 新建一本書完成 ----
            //--- 下面對《哈里波特》做一些修改。 ----
            //--- 查詢找《哈里波特》----
            theBook=(Element) selectSingleNode("/books/book[name='哈里波特']", root);
            System.out.println("--- 查詢找《哈里波特》 ----");
            output(theBook);
            //--- 此時修改這本書的價格 -----
            theBook.getElementsByTagName("price").item(0).setTextContent("15");//getElementsByTagName 返回的是NodeList,所以要跟上item(0)。另外,getElementsByTagName("price")相當於xpath 的".//price"。
            System.out.println("--- 此時修改這本書的價格 ----");
            output(theBook);
            //--- 另外還想加一個屬性id,值為B01 ----
            theBook.setAttribute("id", "B01");
            System.out.println("--- 另外還想加一個屬性id,值為B01 ----");
            output(theBook);
            //--- 對《哈里波特》修改完成。 ----
            //--- 要用id屬性刪除《三國演義》這本書 ----
            theBook=(Element) selectSingleNode("/books/book[@id='B02']", root);
            System.out.println("--- 要用id屬性刪除《三國演義》這本書 ----");
            output(theBook);
            theBook.getParentNode().removeChild(theBook);
            System.out.println("--- 刪除后的XML ----");
            output(xmldoc);
            //--- 再將所有價格低於10的書刪除 ----
            NodeList someBooks=selectNodes("/books/book[price<10]", root);
            System.out.println("--- 再將所有價格低於10的書刪除 ---");
            System.out.println("--- 符合條件的書有 "+someBooks.getLength()+"本。 ---");
            for(int i=0;i<someBooks.getLength();i++) {
                someBooks.item(i).getParentNode().removeChild(someBooks.item(i));
            }
            output(xmldoc);
            saveXml("Test1_Edited.xml", xmldoc);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void output(Node node) {//將node的XML字符串輸出到控制台
        TransformerFactory transFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty("encoding", "utf-8");
            transformer.setOutputProperty("indent", "yes");
            DOMSource source=new DOMSource();
            source.setNode(node);
            StreamResult result=new StreamResult();
            result.setOutputStream(System.out);
            
            transformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        }   
    }
    
    public static Node selectSingleNode(String express, Object source) {//查找節點,並返回第一個符合條件節點
        Node result=null;
        XPathFactory xpathFactory=XPathFactory.newInstance();
        XPath xpath=xpathFactory.newXPath();
        try {
            result=(Node) xpath.evaluate(express, source, XPathConstants.NODE);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
    public static NodeList selectNodes(String express, Object source) {//查找節點,返回符合條件的節點集。
        NodeList result=null;
        XPathFactory xpathFactory=XPathFactory.newInstance();
        XPath xpath=xpathFactory.newXPath();
        try {
            result=(NodeList) xpath.evaluate(express, source, XPathConstants.NODESET);
        } catch (XPathExpressionException e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
    public static void saveXml(String fileName, Document doc) {//將Document輸出到文件
        TransformerFactory transFactory=TransformerFactory.newInstance();
        try {
            Transformer transformer = transFactory.newTransformer();
            transformer.setOutputProperty("indent", "yes");
            DOMSource source=new DOMSource();
            source.setNode(doc);
            StreamResult result=new StreamResult();
            result.setOutputStream(new FileOutputStream(fileName));
            
            transformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            e.printStackTrace();
        } catch (TransformerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }   
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book>
        <name>哈里波特</name>
        <price>10</price>
        <memo>這是一本很好看的書。</memo>
    </book>
    <book id="B02">
        <name>三國演義</name>
        <price>10</price>
        <memo>四大名著之一。</memo>
    </book>
    <book id="B03">
        <name>水滸</name>
        <price>6</price>
        <memo>四大名著之一。</memo>
    </book>
    <book id="B04">
        <name>紅樓</name>
        <price>5</price>
        <memo>四大名著之一。</memo>
    </book>
</books>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM