ITeye博客

Java读写XML工具类

keating · 2010-02-07 14:25 · Java · 编程语言 · Markdown


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * 读xml文件
 */
package util.xml;

import java.io.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.*;
import javax.xml.parsers.*;
import org.xml.sax.SAXException;

public class ReadXML {

    private Vector<Vector<String>> v = null;
    private DocumentBuilder builder;
    private Document doc;

    public ReadXML() {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public Vector<Vector<String>> read(String fileName,String oneName,String[] xmlNames) {
        File file = new File(fileName);
        if (!file.exists()) {
            return null;
        }
        try {
            doc = builder.parse(fileName);
        } catch (SAXException ex) {
            Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        v = new Vector<Vector<String>>();
        try {
            NodeList nl = doc.getElementsByTagName(oneName);
            Vector<String> v_s;
            for (int i = 0; i < nl.getLength(); i++) {
                v_s = new Vector<String>();
                for (int j = 0; j < xmlNames.length; j++) {
                    v_s.add(doc.getElementsByTagName(xmlNames[j]).item(i).getTextContent());
                }
                v.add(v_s);
            }
        } catch (Exception ex) {
            Logger.getLogger(ReadXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        return this.v;
    }
}


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 * 写xml文件
 */
package util.xml;

/**
 *
 * @author Administrator
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
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.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

/**
 * 功能:
 * @author yaos  email: yaos@isoftstone-ai.com
 * @date 2008 11 25
 */
public class WriteXML {

    private DocumentBuilder db;
    private Document doc;
    //配置信息
    private String fileName;
    private String configName;
    private String oneName;
    private String[] xmlNames;

    public WriteXML(String fileName, String configName, String oneName, String[] xmlNames) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            db = dbf.newDocumentBuilder();
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(WriteXML.class.getName()).log(Level.SEVERE, null, ex);
        }
        this.fileName = fileName;
        this.configName = configName;
        this.oneName = oneName;
        this.xmlNames = xmlNames;
    }

    public void write(Vector<Vector<Object>> v) {
        this.deleteFile();//删除文件
        this.doc = db.newDocument();
        Element root = doc.createElement(configName);
        for (Vector<Object> v_s : v) {//保存
            root.appendChild(this.saveOne(v_s));
        }
        this.doc.appendChild(root);
        this.export();//导出文件
    }

    private void deleteFile() {
        File file = new File(fileName);
        if (file.exists()) {
            file.delete();
        }
    }
    //下面的方法是写xml到.xml的文档

    private void export() {
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer;//此实例可以用于处理来自不同源的 XML,并将转换输出写入各种接收器。
        try {
            transformer = tf.newTransformer();
            DOMSource source = new DOMSource(doc);//创建带有 DOM 节点的新输入源
            transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");//设置转换中实际的输出属性
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");//设置转换中实际的输出属性
            OutputStreamWriter pw = new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8");
            StreamResult result = new StreamResult(pw);//从字节流构造 StreamResult 充当转换结果的持有者,可以为 XML、纯文本、HTML 或某些其他格式的标记
            transformer.transform(source, result);//将 XML Source 转换为 Result
            pw.close();//关闭
        } catch (Exception ex) {
            Logger.getLogger(WriteXML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    //将一行数据保存在一个excel中

    private Element saveOne(Vector<Object> v_s) {//用Object
        Element root = doc.createElement(oneName);
        for (int i = 0; i < v_s.size(); i++) {
            Element e = doc.createElement(xmlNames[i]);//
            if (v_s.get(i) == null) {
                e.setTextContent("");//这里有个异常!
            } else {
                e.setTextContent(v_s.get(i).toString());//这里有个异常!
            }
            root.appendChild(e);
        }
        return root;
    }
}

一个例子


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package util.xml;

/**
 *
 * @author Administrator
 */
public class XMLStruct {
    public static String fileName = "cable.xml";
    public static String[] xmlNames = {"始","末","长度"};
    public static String configName = "totalNodes";
    public static String oneName = "subNodes";
}

评论(1)

  1. #1 楼 · keating · 2010-02-07 14:27

    网上随处可淘,写xml文件注意编码即可。

评论功能维护中,当前仅展示历史评论。