欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jdom解析xml文件

程序员文章站 2022-05-28 08:08:33
...
library.xml

<?xml version="1.0" encoding="UTF-8"?>
<books>
<book email="zhoujunhui">
<name>alterrjzjh</name>
<price>60.0</price>
</book>
</books>


package test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


import net.sf.json.JSONObject;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;


public class JDomParse {

public JDomParse(String xmlpath) {
SAXBuilder builder = new SAXBuilder(false);//SAXBuilder是一个JDOM解析器, 能将路径中的XML文件解析为Document对象
try {
Document doc = builder.build(xmlpath);// 得到Document,我们以后要进行的所有操作都是对这个Document操作的:
Element books = doc.getRootElement();// 得到根元素:
List booklist = books.getChildren();// 得到元素(节点)的集合:
Map<String,String> map=new HashMap<String,String>();
for (Iterator iter = booklist.iterator(); iter.hasNext();) {
Element book = (Element) iter.next();
List l1 = book.getChildren();
for(Iterator iter1 = l1.iterator(); iter1.hasNext();){
Element book1 = (Element) iter1.next();
System.out.println(book1.getName()); //获取节点的名称
System.out.println(book1.getValue());//获取节点的值
map.put(book1.getName(), book1.getValue());//把节点名称和节点值放到键值对应的map集合中
}
}
JSONObject json = JSONObject.fromObject(map);//把map转换为json对象
System.out.println(json.toString()); //输出json字符串

} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {

String xmlpath = "library.xml";
new JDomParse(xmlpath);
}
}