`
whj0427
  • 浏览: 37807 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

利用dom4j操作.xml文件

阅读更多
由于工作需要,前些天学习了一下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;
    }

    /**
     * 添加节点
     * <database>
     *   <station>
     *     <datasource name="" laststarttime="" lastendtime=""/>
     *     <datasource name="" laststarttime="" lastendtime=""/>
     *   </station>
     *</database>
     * 添加一个新的结点,(一行<datasource name="" laststarttime="" lastendtime=""/>)
     * 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
     *   <?xml version="1.0" encoding="GBK"?>
     *   <SelectDefineByXML>
     *     <select name="dbsource">
     *       <item option="jdbc/3309"/>
     *       <item option="jdbc/3307"/>
     *     </select>
     *   </SelectDefineByXML>
     * 读取/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());
        }
    }


    /**
     *根据某一特定数据读取/修改文件中某一具体节点的数据
     * 例如文件格式如下
     *   <?xml version="1.0" encoding="GBK"?>
     *   <database>
     *     <station>
     *       <datasource name="jdbc/3307" laststarttime="2007-10-29 17:11:19" lastendtime="2007-10-29 16:40:20"/>
     *       <datasource name="jdbc/3308" laststarttime="2007-10-29 16:46:28" lastendtime="2007-10-29 16:40:30"/>
     *     </station>
     *   </database>
     * 根据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;
    }

    /**
     *读取文件中所有具体节点的数据
     * 例如文件格式如下
     *   <?xml version="1.0" encoding="GBK"?>
     *   <SelectDefineByXML>
     *     <select name="dbsource">
     *       <item option="jdbc/3309"/>
     *       <item option="jdbc/3307"/>
     *     </select>
     *   </SelectDefineByXML>
     * 读取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;
    }


    /**
     *读取/修改某个节点的数据
     * 文件格式如下:
     *   <?xml version="1.0" encoding="GBK"?>
     *   <database>
     *     <center>
     *       <datasource>
     *         <name>db0000</name>
     *       </datasource>
     *     </center>
     *   </database>
     * 读取/修改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;
    }


    /**
     *修改某个节点的数据
     * 文件格式如下:
     *   <?xml version="1.0" encoding="GBK"?>
     *   <database>
     *      <station>
     *        <datasource>
     *          <name>888</name>
     *          <name>111</name>
     *          <name>222</name>
     *          <name>333</name>
     *        </datasource>
     *      </station>
     *   </database>
     * 读取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();
                }
            }
        }
    }

    /**
     *读取/修改某个节点的数据
     * 文件格式如下:
     *   <?xml version="1.0" encoding="GBK"?>
     *   <database>
     *     <center>
     *       <datasource name="db0000"/>
     *     </center>
     *   </database>
     * 读取/修改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;
    }


    /**
     *读取文件中所有具体节点的数据
     * 例如文件格式如下
     *   <?xml version="1.0" encoding="GBK"?>
     *   <SelectDefineByXML>
     *     <select name="dbsource">
     *       <item option="jdbc/3309"/>
     *       <item option="jdbc/3307"/>
     *     </select>
     *   </SelectDefineByXML>
     * 读取/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();
    }

}
分享到:
评论
1 楼 feiniao04 2009-09-19  
想请教一下,假如根节点下面的一级子节点中有很多属性,每个我都需要,具体改如何解析呢。
比方说我有这样一个文件,名称是:gpd.xml

内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<root-container name="purchase" width="1051" height="615">
  <node name="开始填写采购申请" x="300" y="24" width="132" height="36">
    <edge>
      <label x="5" y="-10"/>
    </edge>
  </node>
  <node name="修改采购申请" x="576" y="72" width="132" height="36">
    <edge>
      <label x="5" y="-10"/>
      <bendpoint w1="-157" h1="-2" w2="118" h2="-56"/>
    </edge>
  </node>
  <node name="join1" x="276" y="360" width="177" height="24">
    <edge>
      <label x="5" y="-10"/>
    </edge>
  </node>
  <node name="主管审批" x="432" y="252" width="132" height="36">
    <edge>
      <label x="5" y="-10"/>
    </edge>
  </node>
  <node name="申请人取消申请" x="180" y="252" width="132" height="36">
    <edge>
      <label x="5" y="-10"/>
    </edge>
  </node>
  <node name="fork1" x="288" y="132" width="158" height="24">
    <edge>
      <label x="5" y="34"/>
      <bendpoint w1="128" h1="2" w2="-3" h2="-124"/>
    </edge>
    <edge>
      <label x="-77" y="29"/>
      <bendpoint w1="-124" h1="2" w2="-3" h2="-124"/>
    </edge>
  </node>
  <node name="判断流程流转走向" x="300" y="420" width="132" height="36">
    <edge>
      <label x="5" y="-10"/>
    </edge>
    <edge>
      <label x="5" y="-10"/>
      <bendpoint w1="284" h1="0" w2="8" h2="348"/>
    </edge>
  </node>
  <node name="结束" x="300" y="492" width="132" height="36"/>
</root-container>

我现在想获得所有节点名称为“node”中的 x,y,width还有height的值。
你的方法写的挺好,但是我初次研究解析xml文件的方法,不知如何变通。急盼解答。

相关推荐

Global site tag (gtag.js) - Google Analytics