代码拉取完成,页面将自动刷新
package com.itheima.a03dom4jdemo;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class dom4jDemo1 {
public static void main(String[] args) throws DocumentException {
ArrayList<Person> list = new ArrayList<>();
//1.创建解析器对象
SAXReader saxReader = new SAXReader();
//2.利用解析器去解析xml文件,并返回文档对象
File file = new File("sockethomework\\src\\com\\itheima\\a03dom4jdemo\\person.xml");
Document document = saxReader.read(file);
//3.下面一层一层的扒开获取里面的数据即可
//自己解析的时候一定要一层一层的解析
//获取到根标签
Element rootElement = document.getRootElement();
//4.获取根标签的子标签
List<Element> persons = rootElement.elements("person");
for (Element person : persons) {
//5.继续获取里面的内容
//属性id
Attribute id = person.attribute("id");
String idvalue = id.getText();
//姓名name
Element name = person.element("name");
String namevalue = name.getText();
//年龄age
Element age = person.element("age");
String agevalue = age.getText();
int ageInt = Integer.parseInt(agevalue);
//创建对象
Person p = new Person(idvalue, namevalue, ageInt);
list.add(p);
}
//打印集合
//System.out.println(list);
//用stream流打印IO流
list.stream().forEach(s -> System.out.println(s));
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。