Dom4j的一个小例子,用于解析xml文件的元素获取方式

import java.io.File;

import java.io.IOException;



import javax.xml.parsers.ParserConfigurationException;



import org.dom4j.Document;

import org.dom4j.DocumentException;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

import org.xml.sax.SAXException;



public class Dom4jDemo {

public static void main(String[] args) throws ParserConfigurationException, DocumentException, SAXException, IOException {

SAXReader saxReader = new SAXReader();// new读取的类

Document doc = saxReader.read(new File("F:\\MyEclipse Work\\lj_API\\XML\\com\\luo\\kcit\\XML\\Dom4j\\student.xml"));

// 读取指定的文档

Element root = doc.getRootElement();// 返回元素节点



System.out.println("root element: " + root.getName());// 输出根节点名称



Element e = root.element("student");



Element userId = e.element("userId");//判断是否有userid这个元素,有的话,返回到Element类型的userId

System.out.print(userId.getName()+":"+userId.getData()+" ");

System.out.println("id:" + userId.attributeValue("id"));// 返回元素的字段



Element name = e.element("name");

System.out.println(name.getName() + ": " + name.getData());



Element sex = e.element("sex");

System.out.println(sex.getName()+":"+sex.getData());



}

}
<?xml version="1.0" encoding="UTF-8"?>

<cla>

    <student>

        <userId id="1">A110</userId>

        <name>Toolo</name>

        <age>23</age>

        <sex></sex>

    </student>

</cla>

你可能感兴趣的:(dom4j)