您的位置:首页 > 其它

Dom4J解析XML

2016-08-19 10:07 417 查看
package org.fkjava;

import java.io.InputStream;
import java.util.List;

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

public class TestRead {
/**
* 读取note.xml
*/
public void readNode(){
InputStream is = null;
try {
is=this.getClass().getResourceAsStream("/note.xml");
SAXReader saxReader=new SAXReader();
Document document = saxReader.read(is);
//读取根元素
Element root_node=document.getRootElement();
System.out.println(root_node.getName());
/** <note>/
<to id="1">马航</to>
<from>失联</from>
<heading>飞机去哪儿了</heading>
<body>你快回来</body>
</note>*/
// 读取子元素 to
Element to_node=root_node.element("to");
System.out.println(to_node.getName()+"="+to_node.getText());
//获取子元素to的属性
Attribute attribute=to_node.attribute("id");
System.out.println(attribute.getName()+"="+attribute.getValue());
System.out.println(root_node.element("from").getName()+"="+root_node.element("from").getText());
System.out.println("heading="+root_node.element("heading").getText());
System.out.println("body="+root_node.element("body").getText());
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//不知道元素情况时,解析xml
public void read(){
InputStream is = null;
try {
is=this.getClass().getResourceAsStream("/org/fkjava/note.xml");
Document document = new SAXReader().read(is);
//根元素
Element root_node=document.getRootElement();
System.out.println("根元素名字:"+root_node.getName());
//根元素下面的所有子元素(不包括子元素下面的子元素)
List<Element> child_node_list=root_node.elements();
for(Element child_node:child_node_list){
System.out.println(child_node.getName()+"="+child_node.getText());
//遍历当前子元素的属性
List<Attribute> attributes=child_node.attributes();
for(Attribute attribute:attributes){
System.out.println(attribute.getName()+"="+attribute.getText());
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void readBook(){有疑问
InputStream is = null;
try {
is=this.getClass().getResourceAsStream("/org/fkjava/book.xml");
Document document=new SAXReader().read(is);
//读取根元素books
Element root_node=document.getRootElement();
System.out.println(root_node.getName());
//返回子元素集合
List<Element> child_node_list=root_node.elements();
for(Element child_node:child_node_list){
System.out.println(child_node.getName()+"="+child_node.getText());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
TestRead t = new TestRead();
//t.readNode();
//t.read();
t.readBook();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dom4j