java使用dom讀取,更新xml檔案

來源:互聯網
上載者:User

標籤:java讀取   更新xml檔案   

package com.sun.xml;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.UnsupportedEncodingException;import javax.xml.parsers.DocumentBuilder;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.Node;import org.w3c.dom.NodeList;import org.w3c.dom.Text;import org.xml.sax.SAXException;public class ReadXml {    public static void main(String[] args) throws ParserConfigurationException, TransformerException {        Document document=read("C:\\Users\\Administrator\\Desktop\\bookstore1.xml");        String path="C:\\Users\\Administrator\\Desktop\\bookstore1.xml";        addNode(document, path, "張三");    }    public static Document  read(String path) throws ParserConfigurationException, TransformerException{        Document document=null;        DocumentBuilderFactory bf=DocumentBuilderFactory.newInstance();        DocumentBuilder builder=bf.newDocumentBuilder();        File file=new File(path);        try {            document= builder.parse(file);            //得到值為title的標籤,返回的是集合            NodeList nodeList=document.getElementsByTagName("title");                  for(int i=0;i<nodeList.getLength();i++){                Node node=nodeList.item(i);                String string=node.getTextContent();                System.out.println(string);                updateXmlNode(document, node, "sssss", path);            }                    } catch (SAXException | IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }        return document;    }    public static void updateXmlNode(Document document,Node node,String text,String path) throws TransformerException, UnsupportedEncodingException, FileNotFoundException{        node.setTextContent(text);        writeToFile(document, path);    }        public static void addNode(Document document,String path,String text){        Text text2=document.createTextNode(text);        Text text3=document.createTextNode(text);        Text text4=document.createTextNode(text);                Element element=document.createElement("book");        Element element2=document.createElement("title");        Element element3=document.createElement("author");            Element element4=document.createElement("price");                element2.appendChild(text2);        element3.appendChild(text3);        element4.appendChild(text4);        element.appendChild(element2);        element.appendChild(element3);        element.appendChild(element4);        NodeList nodeList= document.getElementsByTagName("bookstore");         Node node=nodeList.item(0);        node.appendChild(element);        try {            writeToFile(document, path);        } catch (UnsupportedEncodingException | FileNotFoundException                | TransformerException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }        public static void writeToFile(Document document,String path) throws TransformerException, UnsupportedEncodingException, FileNotFoundException{        TransformerFactory transformerFactory=TransformerFactory.newInstance();        Transformer transformer=transformerFactory.newTransformer();        /*         * 格式化輸出xml文檔,換行和縮排*/          transformer.setOutputProperty(OutputKeys.INDENT, "yes");          transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");        //transformer.transform(new DOMSource(document), new StreamResult(path));        /*         * 設定輸出資料流的編碼為UTF-8*/        OutputStreamWriter oWriter=new OutputStreamWriter(new FileOutputStream(new File(path)),"UTF-8");        document.setXmlStandalone(true);        transformer.transform(new DOMSource(document),new StreamResult(oWriter));    }}


xml檔案如下:

<?xml version="1.0" encoding="utf-8"?> <bookstore>   <!--記錄書本的資訊-->   <book>    <title>資料結構</title>    <author>嚴蔚敏</author>    <price>30.00</price>  </book></bookstore>


本文出自 “matengbing” 部落格,請務必保留此出處http://matengbing.blog.51cto.com/11395502/1876353

java使用dom讀取,更新xml檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.