
org.jdom jdom2.0.2
二、创建xml文件(StudentList.xml)如果不想使用maven方式,那么手动下载jdom的jar
Jdom.jar 下载地址
三、创建项目进行项目解析 演示001 张三 游泳 看书 002 李四 打游戏 打电玩 003 王五 学习 敲代码
public static void main(String[] args) {
//1.创建SAXBuilder对象
SAXBuilder saxBuilder = new SAXBuilder();
try {
//2.创建输入流
InputStream is = new FileInputStream(new File("D:\JavaWork\xML解析\src\Students.xml"));
//3.创建document对象
document document = saxBuilder.build(is);
//4.获取xml文件的父节点
Element rootElement = document.getRootElement();
//演示一 获取每个学生对象信息
//获取父节点下的每个子节点(student)
for (Element child : rootElement.getChildren()) {
//获取标签的属性值
System.out.println(child.getAttribute("code").getValue());
//获取student节点下面的每个节点(id,name,happys)
for (Element item : child.getChildren()){
//输出student节点的子节点内容
System.out.println(item.getText().trim());
//获取happys下面的子节点
for (Element itemChild : item.getChildren()) {
System.out.println(itemChild.getText().trim());
}
}
System.out.println();
}
//演示二 获取每个学生对象信息
for (Element child : rootElement.getChildren()) {
System.out.println(child.getChild("id").getText());
System.out.println(child.getChild("name").getText());
for (Element happys : child.getChild("happys").getChildren()) {
System.out.println(happys.getText());
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
四、运行效果如下
演示一效果图
演示二效果图
五、常用方法六、注意点1、getChildren() 无参 获取当前节点下面的子节点 返回 List
2、getChild("ElementName") 传递要查找的节点名称 查找指定名称的节点 返回 Element对象
3、getText() 无参 获取节点的值 返回String字符串
4、getAttribute("AttrbuteName") 传递要查找的属性名称 查找指定名称的属性对象 返回 Attribute对象
5、getValue() 无参 获取指定属性对象的属性值 返回String 字符串
七、可以借鉴Java解析XML(4种方法)1、getChildren()方法只是获取子节点,并不会获取孙节点
2、xml文件中只能有一个父节点,不能有多个,如上StudentList.xml中的Students
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)