XML读写相关操作

 

import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
 * XML相关操作
 * 
 * @author nassir wen
 */
public class XmlHelper {

    /**
     * 
     * 通过已知xml字符串创建document对象
     * 参考:http://dennis-zane.iteye.com/blog/57542
     * @param xmlStr
     * @return
     * @throws DocumentExceptionss
     */
    public static Document createDocByXmlStr(String xmlStr)
            throws DocumentException {
        return DocumentHelper.parseText(xmlStr);
    }

    /**
     * 
     * 通过xml文件路径创建已知字符串document对象
     * 
     * @param path
     * @return
     * @throws DocumentException
     */
    public static Document createDocByPath(String path)
            throws DocumentException {
        SAXReader saxReader = new SAXReader();
        return saxReader.read(path);
    }

    /**
     * 通过xml字节流Document对象
     * 
     * @return
     */
    public static Document createDoc(InputStream in) throws DocumentException {
        SAXReader saxReader = new SAXReader();
        return saxReader.read(in);
    }

    /**
     * 创建Document对象
     * 
     * @return
     */
    public static Document createDoc() {
        return DocumentHelper.createDocument();
    }

    /**
     * 获取单个node
     * 
     * @param xPath
     * @return
     */
    public static Node getNode(Document doc, String xPath) {
        return doc.selectSingleNode(xPath);
    }

    /**
     * 获取集合nodes
     * 
     * @param xPath
     * @return
     */
    public static List<Node> getNodes(Document doc, String xPath) {
        return doc.selectNodes(xPath);
    }

    /**
     * 获取属性值
     * 
     * @param node
     * @param attrName
     * @return
     */
    public static String getAttrVal(Node node, String attrName) {
        Element e = (Element) node;
        return e.attributeValue(attrName);
    }

    /**
     * 返回构造好的xml字符串
     * 
     * @param doc
     * @return
     */
    public static String outXmlStr(Document doc) {
        return doc.asXML();
    }

    /**
     * 保存xml到文件
     * 
     * @param fileName
     * @param doc
     * @throws IOException
     */
    public static void saveXml(String fileName, Document doc)
            throws IOException {// 将Document输出到文件
        // 读取文件
        FileWriter fileWriter = new FileWriter(fileName);
        // 设置文件编码
        OutputFormat xmlFormat = new OutputFormat();
        xmlFormat.setEncoding("GB2312");
        // 创建写文件方法
        XMLWriter xmlWriter = new XMLWriter(fileWriter, xmlFormat);
        // 写入文件
        xmlWriter.write(doc);
        // 关闭
        xmlWriter.close();
    }

    public static void main(String[] args) {
        // 测试
        try {
            Document doc = XmlHelper.createDoc();
            // 设置编码
            doc.setXMLEncoding("GB2312");
            Element root = doc.addElement("root");
            Element op_code = root.addElement("op_code");
            Element op_name = root.addElement("op_name");
            Element op_user = root.addElement("op_user");
            Element op_passwd = root.addElement("op_passwd");
            Element op_time = root.addElement("op_time");
            Element sp_id = root.addElement("sp_id");
            Element package_id = root.addElement("package_id");
            Element total_num = root.addElement("total_num");
            Element total_amt = root.addElement("total_amt");
            Element client_ip = root.addElement("client_ip");
            op_code.setText("1013");
            op_name.setText("batch_draw");
            // 测试attr 生成
            op_name.addAttribute("test", "1001");
            op_user.setText("");
            op_passwd.setText("");
            op_time.setText("");
            sp_id.setText("");
            package_id.setText("");
            total_num.setText("");
            total_amt.setText("");
            client_ip.setText("");
            // 付款记录
            Element record_set = root.addElement("record_set");
            Element record = record_set.addElement("record");
            Element serial = record.addElement("serial");
            Element rec_bankacc = record.addElement("rec_bankacc");
            Element bank_type = record.addElement("bank_type");
            Element rec_name = record.addElement("rec_name");
            Element pay_amt = record.addElement("pay_amt");
            Element acc_type = record.addElement("acc_type");
            Element area = record.addElement("area");
            Element city = record.addElement("city");
            Element subbank_name = record.addElement("subbank_name");
            Element desc = record.addElement("desc");
            serial.setText("");
            rec_bankacc.setText("");
            bank_type.setText("");
            rec_name.setText("");
            pay_amt.setText("");
            acc_type.setText("");
            area.setText("");
            city.setText("");
            subbank_name.setText("");
            desc.setText("");
            System.out.println(XmlHelper.outXmlStr(doc));
            XmlHelper.saveXml("tenpay.xml", doc);
            // 读取
            Document docXml = XmlHelper.createDocByPath("tenpay.xml");
            System.out.println(XmlHelper.getNode(docXml,"//root/op_code").getText());
            // 获取属性名称
            System.out.println("arrt: "
                    + XmlHelper.getAttrVal(XmlHelper.getNode(docXml,"//root/op_name"),
                            "test"));
            System.out.println("-----------------------------------------------------");
            Document docStr = XmlHelper.createDocByXmlStr("<person> <name>James</name> </person>");
            System.out.println(XmlHelper.getNode(docStr,"//person/name").getText());
        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(xml,dom4j,sax)