论坛首页 入门技术论坛

入门:用dom4j 解析xml 和生成xml

浏览 3504 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-11-08   最后修改:2009-11-08
xml/students.xml

<?xml version="1.0" encoding="UTF-8"?>
<students> 
    <student sn="1"> 
        <name>张三</name> 
        <age>18</age> 
        <college leader="one">TingHua University</college>
        <telephone>01011111111</telephone>
        <notes>Best students!</notes>
    </student> 
    <student sn="2"> 
        <name>李四</name> 
        <age>20</age>
        <college leader="two">BeiJing University</college>
        <telephone>01022222222</telephone> 
        <notes>Better students!</notes>
    </student>
    <student> 
        <name>王五</name> 
        <age>22</age>
        <college>JiaLiDun University</college>
        <telephone>01033333333</telephone> 
        <notes>Bad students!</notes>
    </student> 
</students>

 

1.Dom4jReadExample.java
package com.dom4j;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 利用dom4j解析XML
 *
 * @author Daniel Cheng
 */
public class Dom4jReadExample {
    /**
     * 遍历整个XML文件,获取所有节点的值与其属性的值,并放入HashMap中
     *
     * @param filename
     *            String 待遍历的XML文件(相对路径或者绝对路径)
     * @param hm
     *            HashMap
     *            存放遍历结果,格式:<nodename,nodevalue>或者<nodename+attrname,attrvalue>
     */
    public void iterateWholeXML(String filename, HashMap<String, String> hm) {
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new File(filename));
            Element root = document.getRootElement();
            // 用于记录学生编号的变量
            int num = -1;
            // 遍历根结点(students)的所有孩子节点(student节点)
            for (Iterator<?> iter = root.elementIterator(); iter.hasNext();) {
                Element element = (Element) iter.next();
                num++;
                // 获取student节点的sn编号属性的值
                Attribute snAttr = element.attribute("sn");
                if (snAttr != null) {
                    String sn = snAttr.getValue();
                    if (sn != null && !sn.equals("")) {
                        hm.put(element.getName() + "-" + snAttr.getName()
                                + num, sn);
                    } else {
                        hm.put(element.getName() + "-" + snAttr.getName()
                                + num, ""+(num+1));
                    }
                } else {
                    hm.put(element.getName() + "-sn" + num,""+(num+1));
                }
                // 遍历student结点的所有孩子节点(即name,college,telephone,notes),并进行处理
                for (Iterator<?> iterInner = element.elementIterator(); iterInner
                        .hasNext();) {
                    Element elementInner = (Element) iterInner.next();
                    if (elementInner.getName().equals("college")) {
                        hm.put(elementInner.getName() + num, elementInner
                                .getText());
                        // 获取college节点的leader属性的值
                        Attribute leaderAttr = elementInner.attribute("leader");
                        if (leaderAttr != null) {
                            String leader = leaderAttr.getValue();
                            if (leader != null && !leader.equals("")) {
                                hm.put(elementInner.getName() + "-"
                                        + leaderAttr.getName() + num, leader);
                            } else {
                                hm.put(elementInner.getName() + "-"
                                        + leaderAttr.getName() + num, "leader");
                            }
                        } else {
                            hm.put(elementInner.getName() + "-leader" + num,
                                    "leader");
                        }
                    } else {
                        hm.put(elementInner.getName() + num, elementInner
                                .getText());
                    }
                }
            }

        } catch (DocumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
   
    public static void main(String[]args){
        HashMap<String, String> hm=new HashMap<String, String>();
        new Dom4jReadExample().iterateWholeXML("xml/students.xml",hm);
        System.out.println(hm.size());
        System.out.println(hm.toString());
    }
}
2.Dom4jXML.java
/*用dom4j生成xml*/
package com.dom4j;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class Dom4jXML {
/**
* 利用dom4j生成XML
*
* @author Daniel Cheng
*/

public void createXML() {
//用工厂类创建一个document实例
Document doc = DocumentHelper.createDocument();
//创建根元素emps
Element rootEle = doc.addElement("emps");
//添加注释
rootEle.addComment("这是一个dom4j生成的xml文件");
//emps根节点下创建一个emp节点
Element empEle = rootEle.addElement("emp");
//emp添加属性id="1"
empEle.addAttribute("id", "1");
//emp节点下创建一个name节点
Element nameEle = empEle.addElement("name");
//name节点下创建一个文本节点zhangsan
nameEle.setText("Daniel Cheng");
//再为name节点创建一个兄弟节点
Element sexEle = empEle.addElement("sex");
sexEle.setText("man");
//将document中的内容写入文件中
try {
Writer out = new FileWriter("xml/emps.xml");
//格式化输出,类型IE浏览一样
OutputFormat format = OutputFormat.createPrettyPrint();
//OutputFormat format = OutputFormat.createCompactFormat();
format.setEncoding("UTF-8");
//创建写出对象
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
writer.close();
System.out.println("生成emps.xml成功。");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("失败了。");
}
}
public static void main(String[] args) {
new Dom4jXML().createXML();
}

} 

 

xml/emps.xml文档内容
<?xml version="1.0" encoding="UTF-8"?>

<emps>
  <!--这是一个dom4j生成的xml文件-->
  <emp id="1">
    <name>Daniel Cheng</name>
    <sex>man</sex>
  </emp>
</emps>

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics