Java中Dom4j解析XML

来源:互联网 发布:spss 贝叶斯网络示例 编辑:程序博客网 时间:2024/05/18 15:27

任务

使用Java,利用dom4j类库解析XML文件,获取指定节点属性的值

代码

具体详细细节,可参考博客(很详尽):
http://blog.csdn.net/yyywyr/article/details/38359049

我主要是根据自己需要,做了小改动:

import java.io.File;import java.util.Iterator;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * dom4j解析XML文件,获取指定节点属性的值 * ParseXML.java * @author xianggen * @date 2016年8月3日 上午10:01:40 */public class ParseXML {    //获取指定节点属性的值    public static String AmtDeviceNumLimit;    public static String AmtChannelNumLimit;    public static String AmtClentUserLimit;    public static String AmtdefenceNum;    public static void main(String[] args) throws DocumentException {        SAXReader saxReader = new SAXReader();        Document document = saxReader.read(new File("E:/license.xml"));        Element root = document.getRootElement();            // 获取根元素        traverseNodes(root);        print();    }    /**     * 遍历当前节点下的所有节点     * @param node     */    public static void traverseNodes(Element node) {        // 如果当前节点内容不为空        if (!(node.getTextTrim().equals(""))) {            if ("AmtDeviceNumLimit".equals(node.getName())) {                AmtDeviceNumLimit = node.getText();            }else if ("AmtChannelNumLimit".equals(node.getName())) {                AmtChannelNumLimit = node.getText();            } else if ("AmtClentUserLimit".equals(node.getName())) {                AmtClentUserLimit = node.getText();            } else if ("AmtdefenceNum".equals(node.getName())) {                AmtdefenceNum = node.getText();            } else {            }        }        // 同时递归 迭代当前节点下面的所有子节点        @SuppressWarnings("unchecked")        Iterator<Element> iterator = node.elementIterator();        while (iterator.hasNext()) {            Element e = iterator.next();            traverseNodes(e);        }    }    /**     * 打印指定属性的值     */    public static void print(){        StringBuffer sb = new StringBuffer();        sb.append("AmtDeviceNumLimit="+AmtDeviceNumLimit+"\n");        sb.append("AmtChannelNumLimit="+AmtChannelNumLimit+"\n");        sb.append("AmtClentUserLimit="+AmtClentUserLimit+"\n");        sb.append("AmtdefenceNum="+AmtdefenceNum+"\n");        System.out.println(sb.toString());    }}
0 0
原创粉丝点击