DOM4j

import org.dom4j.Document;   
import java.util.List;   
import java.util.Iterator;   
import org.dom4j.Element;   
import org.dom4j.Attribute;   
import org.dom4j.io.SAXReader;   
import java.io.File;   
import java.io.InputStream;   
import java.util.ArrayList;   
import java.io.IOException;   
import org.dom4j.io.OutputFormat;   
import org.dom4j.io.XMLWriter;   
import java.io.FileOutputStream;   
  
public class XmlFile {   
  
    /**  
     * 载入一个文件  
     * 不只限于.xml,也可是.txt等  
     * */  
    public static Document loadFile(String filename) {   
        Document document = null;   
        try {   
            SAXReader saxReader = new SAXReader();   
            document = saxReader.read(new File(filename));   
        } catch (Exception ex) {   
            ex.printStackTrace();   
        }   
        return document;   
    }   
  
    /**  
     * 添加节点  
     * 
 
 
  
    
     *   
  
  
   
     
     *     
   
     
     *     
   
     
     *   
  
    
     *
 
   
     * 添加一个新的结点,(一行
 
 )  
     * fileName:文件名,node[]:节点(以上面的文件为例,添加一个新的 datasource ,node[]={"station","datasource"}),attribute[]:Attribute列表(以上面的文件为例,attribute[]={"name","laststarttime","lastendtime"})  
     * */  
    public static void xmlAddNode(String fileName, String[] node,   
                                  String[] attribute, String[] value) {   
        Document doc = loadFile(fileName);   
        Element element = doc.getRootElement();   
        for (int i = 0; i < node.length - 1; i++) {   
            element = element.element(node[i]);   
        }   
        element = element.addElement(node[node.length - 1]);   
        for (int i = 0; i < attribute.length; i++) {   
            element.addAttribute(attribute[i], value[i]);   
        }   
        try {   
            saveDoc(doc, fileName);   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
  
    /**  
     *输出文件中所有具体节点的数据  
     * 例如文件格式如下  
     * SelectFromXML.xml  
     *   
 
   
     *   
 
 
  
    
     *     
  
  
  • * * * *
  • * 读取/SelectDefineByXML/select/item里option的值 * fileName文件名,rootnode根节点,attributename要读取的Attribute * 调用方式:xmlRead("/SelectFromXML.xml","/SelectDefineByXML/select/item","option"); * 同parserXML(String fileName)功能一样,只是parserXML有返回值 * */ public static void xmlRead(String fileName, String rootnode, String attributename) { Document doc = loadFile(fileName); List list = doc.selectNodes(rootnode); Iterator it = list.iterator(); while (it.hasNext()) { Element element = (Element) it.next(); Attribute intem = element.attribute(attributename); System.out.println(attributename + ":" + intem.getValue()); } } /** *根据某一特定数据读取/修改文件中某一具体节点的数据 * 例如文件格式如下 * * * * * * * * 根据name的值读取/修改lastendtime的值 * fileName文件名,rootnode根节点(如:/database/station/datasource) * attributename要读取的Attribute名(如:lastendtime) * referenceattribute参考Attribute名(如:name) * referencevalue参考Attribute的值 * attributevalue修改时attributename要改为的值 * mod:true 修改,false:读取 * 调用方式:lastendtime = xmlfile.xmlReadOrMod("/databaselog.xml","/database/station/datasource","lastendtime","name","jdbc/3007","2007-11-1 10:18:57", true); * */ public static String xmlReadOrMod(String fileName, String rootnode, String attributename, String referenceattribute, String referencevalue, String attributevalue, boolean mod) { String result = ""; Document doc = loadFile(fileName); List list = doc.selectNodes(rootnode); Iterator it = list.iterator(); while (it.hasNext()) { Element element = (Element) it.next(); Attribute endnode_ = element.attribute(attributename); Attribute reference_ = element.attribute(referenceattribute); if (reference_.getValue().equals(referencevalue)) { result = endnode_.getValue(); if (mod) { try { endnode_.setValue(attributevalue); saveDoc(doc, fileName); break; } catch (Exception e) { e.printStackTrace(); } } break; } } return result; } /** *读取文件中所有具体节点的数据 * 例如文件格式如下 * * *
  • * * * *
  • * 读取rootnode(select)/node(item)里attribute(option)的值 * 同xmlRead(String fileName)功能一样,只是xmlRead没有返回值 * 如果要得到option的值,方法调用的时候:parserXML("文件名","select","item", "option"); * */ public List parserXML(String fileName, String rootnode, String node, String attribute) { ArrayList list = new ArrayList(); try { Document doc = loadFile(fileName); Element root = doc.getRootElement(); // 解析rootnode集合 for (Iterator i = root.elementIterator(rootnode); i.hasNext(); ) { Element select = (Element) i.next(); Iterator k = select.elementIterator(node); while (k.hasNext()) { Element item = (Element) k.next(); Attribute aOption = item.attribute(attribute); list.add(aOption.getValue()); } } } catch (Exception e) { e.printStackTrace(); } return list; } /** * 同parserXML(String fileName, String rootnode, String node,String attribute)作用一样 * 同parserXML的区别,parserXmlRead从类路径读取文件 */ public List parserXmlRead(String fileName, String rootnode, String node, String attribute) { ArrayList list = new ArrayList(); try { // 从类路径读取配置文件。 InputStream stream = getClass().getResourceAsStream( fileName); SAXReader reader = new SAXReader(); Document doc = reader.read(stream); Element root = doc.getRootElement(); // 解析rootnode集合 for (Iterator i = root.elementIterator(rootnode); i.hasNext(); ) { Element select = (Element) i.next(); Iterator k = select.elementIterator(node); while (k.hasNext()) { Element item = (Element) k.next(); Attribute aOption = item.attribute(attribute); System.out.println(aOption.getValue()); list.add(aOption.getValue()); } } } catch (Exception e) { e.printStackTrace(); } return list; } /** *读取/修改某个节点的数据 * 文件格式如下: * * *
    * * db0000 * *
    * * 读取/修改name的值(database/center/datasource的name值),filename文件名,rootnode根节点 * 当mod=true时修改 * 适用于取得单个值 * */ public static String xmlReadOrMod(String filename, String node, boolean mod, String modvalue) { Document doc = loadFile(filename); /** 直接取得 node 的值 */ List list = doc.selectNodes(node); Iterator it = list.iterator(); String result = ""; Element hostElement = (Element) it.next(); result = hostElement.getText(); //如果mod=true那么修改并保存 if (mod) { System.out.println(mod); hostElement.setText(modvalue); try { saveDoc(doc, filename); } catch (Exception e) { e.printStackTrace(); } } System.out.println(hostElement.getText()); return result; } /** *修改某个节点的数据 * 文件格式如下: * * * * * 888 * 111 * 222 * 333 * * * * 读取name的值(database/station/datasource/name值),如果某一个值==recvalue,则修改为value * filename文件名,node节点,返回String * */ public static void xmlMod(String filename, String node, String recvalue, String value) { Document doc = loadFile(filename); /** 直接取得 node 的值 */ List list = doc.selectNodes(node); Iterator it = list.iterator(); while (it.hasNext()) { Element hostElement = (Element) it.next(); System.out.println("hostElement=" + hostElement.getText()); //修改node的值 if (hostElement.getText().equals(recvalue)) { hostElement.setText(value); try { saveDoc(doc, filename); } catch (Exception e) { e.printStackTrace(); } } } } /** *读取/修改某个节点的数据 * 文件格式如下: * * *
    * *
    * * 读取/修改name的值(database/center/datasource/@name值) * filename文件名,node节点,返回String * mod:true 修改,false 读取 * modvalue修改值 * */ public static String xmlMod(String filename, String node, boolean mod, String modvalue) { Document doc = loadFile(filename); /** 直接取得 node 的值 */ List list = doc.selectNodes(node); Iterator it = list.iterator(); String result = ""; if (it.hasNext()) { Attribute attribute = (Attribute) it.next(); result = attribute.getValue(); //修改node的值 if (mod) { try { attribute.setValue(modvalue); saveDoc(doc, filename); } catch (Exception e) { e.printStackTrace(); } } } return result; } /** *读取文件中所有具体节点的数据 * 例如文件格式如下 * * *
  • * * * *
  • * 读取/SelectDefineByXML/select/item里option的值 * 同 xmlRead(String fileName),parserXML(String fileName) 功能一样 * */ public static void xmlReadNode(String filename, String rootnode, String node) { Document doc = loadFile(filename); List list = doc.selectNodes(rootnode); Iterator it = list.iterator(); /** 直接用属性path取得name值 */ list = doc.selectNodes(rootnode + "/@" + node); it = list.iterator(); while (it.hasNext()) { Attribute attribute = (Attribute) it.next(); System.out.println("@node=" + attribute.getValue()); } } /** * 保存XML文档 * @param doc * @throws IOException */ public static void saveDoc(Document doc, String savefilename) throws IOException { OutputFormat format = OutputFormat.createPrettyPrint(); XMLWriter writer = new XMLWriter(new FileOutputStream(savefilename), format); writer.write(doc); writer.close(); } }
     
    • 0
      点赞
    • 0
      收藏
      觉得还不错? 一键收藏
    • 0
      评论

    “相关推荐”对你有帮助么?

    • 非常没帮助
    • 没帮助
    • 一般
    • 有帮助
    • 非常有帮助
    提交
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

    当前余额3.43前往充值 >
    需支付:10.00
    成就一亿技术人!
    领取后你会自动成为博主和红包主的粉丝 规则
    hope_wisdom
    发出的红包
    实付
    使用余额支付
    点击重新获取
    扫码支付
    钱包余额 0

    抵扣说明:

    1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
    2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

    余额充值