1、JDOM是基于DOM和SAX方式的扩展方法,基于树形结构,采用纯JAVA 的技术对XML文档实现解析、生成、序列化及多种操作。
2、具体解析方法及源码说明
public class JDOMTest {
private static ArrayList<Book> booksList = new ArrayList<Book>();
public static void main(String[] args) {
//1.创建一个SAXBuilder的对象
SAXBuilder saxBuilder = new SAXBuilder();
InputStream in = null;
try {
//2.创建一个输入流,将xml文件加载到输入流中
in = new FileInputStream("xmlPractise/books.xml");
//3.通过saxBuilder的build方法,将输入流加载到saxbuilder中
Document document = saxBuilder.build(in);
//4.通过document对象获取xml文件的根节点
Element rootElement = document.getRootElement();
//5.获取根节点下的子节点的list集合
List<Element> bookList = rootElement.getChildren();
//继续进行解析
for(Element book : bookList){
Book bk = new Book();
System.out.println("======开始解析第" + (bookList.indexOf(book)+1) + "本书======");
//知道节点下属属性名称时,获取节点值
//book.getAttributeValue("id");
//解析book的属性集合(针对不清楚book节点下属性的名字及数量)
List<Attribute> attrList = book.getAttributes();
for(Attribute attr : attrList){
//获取属性名
String attrName = attr.getName();
//获取属性值
String attrValue = attr.getValue();
System.out.println("属性名:" + attrName + "--属性值:" + attrValue);
if(attrName.equals("id")){
bk.setId(attrValue);
}
}
//对book节点的子节点的节点名和节点值的遍历
List<Element> bookChildren = book.getChildren();
for(Element child : bookChildren){
System.out.println("节点名:" + child.getName() + "--节点值:" + child.getValue());
if(child.getName().equals("name")){
bk.setName(child.getValue());
}else if(child.getName().equals("author")){
bk.setAuthor(child.getValue());
}else if(child.getName().equals("year")){
bk.setYear(child.getValue());
}else if(child.getName().equals("price")){
bk.setPrice(child.getValue());
}else if(child.getName().equals("language")){
bk.setLanguage(child.getValue());
}
}
System.out.println("======结束解析第" + (bookList.indexOf(book)+1) + "本书======");
booksList.add(bk);
bk = null;
System.out.println(booksList.size());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
附:xml内容
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book id="1">
<name>冰与火之歌</name>
<author>乔治马丁</author>
<year>2014</year>
<price>89</price>
</book>
<book id="2">
<name>小王子</name>
<year>2004</year>
<price>34</price>
<language>English</language>
</book>
</bookstore>