package com.imooc.learn3;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
public class JDomTest {
public static void main(String[] args) throws JDOMException, IOException {
//对Books.xml进行解析
SAXBuilder saxBuilder=new SAXBuilder();
//创建一个输入流
FileInputStream in=new FileInputStream("demo/Books.xml");
//通过SaxBuilder来处理文件输入流
Document document=saxBuilder.build(in);
//通过document对象来获取xml的根节点
Element root=document.getRootElement();
//通过getChildren来获取根节点下面子节点的集合
List<Element> aList=root.getChildren();
//通过For循环来遍历
for (Element element : aList) {
System.out.println("====开始解析第"+(aList.indexOf(element)+1)+"本书====");
System.out.println(element.getName()+"----");
List<Attribute> attrList=element.getAttributes();
//遍历attrList,对于不知道节点的属性名和值
for (Attribute attribute : attrList) {
System.out.println("属性名是:"+attribute.getName());
System.out.println("该属性值是"+attribute.getValue());
}
//针对book的子节点的节点名和节点值进行遍历
List<Element> chiList=element.getChildren();
for (Element elechild : chiList) {
System.out.println("节点名字是:"+elechild.getName()+"节点值是:"+elechild.getValue());
//
System.out.println();
}
System.out.println("====结束解析第"+(aList.indexOf(element)+1)+"本书====");
}
}
}
使用Java的JDOM解析xml代码
原创
©著作权归作者所有:来自51CTO博客作者wx5e6caa8b9792d的原创作品,请联系作者获取转载授权,否则将追究法律责任
下一篇:POST和Get的区别
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
MybatisPlus基础Xml使用教程
MybatisPlus基础最全教程,里面包含操作的核心教程以及重点难点,很适合新手以及中高级开发学习
mybatis mybatisplus springboot -
简单使用JDOM解析XML
当今流行的各种语言,包括Jav
xml java vbscript 文档 email -
JDom,jdom解析xml文件
1.要解析的文件模板如下:
xml 文档 对象 类 jar -
xml解析之JDOM
JDOM是使用Java语言编写的用于读、写、操作XML的一套组件。 要生成的XML文件
xml jdom XML System java -
xml的Jdom解析过程详解
xml的Jdom解析过程详解
职场 休闲 xml Jdom 解析 -
JDOM+XPATH解析XML
JDOM+XPath解析XML的一个小实例
Java XML XPath 解析 JDOM