XML文件的解析 Dom4J

public class Dom4JHelloWorldDemo1 {
@Test
public void passXMLData() throws Exception{
SAXReader saxReader = new SAXReader();
//Document document = saxReader.read(new File("xml-app\\src\\Contacts.xml"));//需要通过模块取定位
////Document document = saxReader.read(new FileInputStream("xml-app\\src\\Contacts.xml"));

//注意:/ 是直接去src下寻找的文件
InputStream is = saxReader.getClass().getResourceAsStream("/Contacts.xml");
Document document = saxReader.read(is);

//3.获取根元素对象
Element root = document.getRootElement();
System.out.println(root.getName());//取得根元素名称

//4.拿根元素下的全部子元素对象(一级,直接儿子)
//List<Element> sonList = root.elements();//拿到所有子元素
List<Element> sonList = root.elements("contact");
for (Element element :sonList) {
System.out.println(element.getName());
}
//拿某个子元素
Element userEle = root.element("user");
System.out.println(userEle.getName());


//默认提取第一个子元素对象(潘金莲)
Element contact = root.element("contact");
//获取子元素文本
System.out.println(contact.elementText("name"));
//去掉前后空格
System.out.println(contact.elementTextTrim("name"));//潘金莲前后空格没有了
//根据元素获取属性值
Attribute idAttr = contact.attribute("id");
System.out.println(idAttr.getName() +"-->"+ idAttr.getValue());
//直接提取属性值
System.out.println(contact.attributeValue("id"));
System.out.println(contact.attributeValue("vip"));

//获取当前元素下的子元素对象
Element email = contact.element("email");
System.out.println(email.getText());

}
}



<?xml version="1.0" encoding="UTF-8"?>
<contactList>
<contact id="1" vip="true">
<name> 潘金莲 </name>
<gender>女</gender>
<email>panpan@itcast.cn</email>
</contact>
<contact id="2" vip="false">
<name>武松</name>
<gender>男</gender>
<email>wusong@itcast.cn</email>
</contact>
<contact id="3" vip="false">
<name>武大狼</name>
<gender>男</gender>
<email>wuda@itcast.cn</email>
</contact>
<user>
</user>
</contactList>

posted on 2022-04-06 10:30  我要当程序源  阅读(18)  评论(0编辑  收藏  举报

导航