首页 > 编程语言 > 详细

java使用dom读取,更新xml文件

时间:2016-11-24 21:58:22      阅读:239      评论:0      收藏:0      [点我收藏+]
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文件

原文:http://matengbing.blog.51cto.com/11395502/1876353

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!