XML解析之Jdom解析

来源:互联网 发布:荷兰红灯区知乎 编辑:程序博客网 时间:2024/05/16 03:08
jdom解析:
        (1)使用JDOM首先要指定使用什么解析器。如:
    SAXBuilder builder=new SAXBuilder(); 这表示使用的是默认的解析器
(2)得到Document,我们以后要进行的所有操作都是对这个Document操作的:
    InputStream input = new FileInputStream("student.xml");
    Document document = builder.build(input);// 获得文档对象
(3)得到根元素:
    Element books=doc.getRootElement();
    
(4)得到元素(节点)的集合:

     List booklist=books.getChildren("student");

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package bean;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
/**
 *  jdom解析xml文件
 * @author tingiting123
 *
 */
public class XmlParse2 {
    public  void xmlParse() throws Exception {
        SAXBuilder builder = new SAXBuilder();//获取解析器
        InputStream input = new FileInputStream("student.xml");//将配置文件转换为字节流
        Document document = builder.build(input);// 获得文档对象
        Element root = document.getRootElement();// 获得根节点
        List<Element> list = root.getChildren(); //获取根节点下的所有子节点
        for (Element e : list) {
            System.out.println("id=" + e.getAttributeValue("id"));
            System.out.println("username=" + e.getChildText("username")+"\t"+"password=" + e.getChildText("password"));
        }
    }
    public static  void main(String ars[]) throws Exception {
        XmlParse2 xp = new XmlParse2();
        xp.xmlParse();// 解析XML
    }
}

student.xml

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8"?>
<persons>
    <person id="1">
    <username>张三</username>
    <password>123123</password>
    </person>
    <person id="2">
    <username>李四</username>
    <password>123456yy</password>
    </person>
</persons>

运行结果:

id=1
username=张三 password=123123
id=2
username=李四 password=123456yy


         
0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 淘宝不支持七天无理由退货怎么办 微信视频横屏怎么办 房子里潮气太重怎么办 淘宝不小心注销了怎么办 淘宝号不小心注销了怎么办 xp网络驱动没了怎么办 淘宝卖家客服态度差怎么办 怀孕吃辣椒喉咙好痛怎么办 淘宝店铺建议不要提交认证怎么办 淘宝买东西商家不退款怎么办 淘宝买东西商家不发货怎么办 在微信上买东西被骗了怎么办 新浪微博自动关注人怎么办 搜淘宝找不到关键词和店铺怎么办 小超市开在一起竞争太大怎么办 淘宝店铺被投诉盗图怎么办 充电宝ic坏了怎么办 淘宝店宝贝权重下降怎么办 淘宝卖家评分低怎么办 淘宝买东西客服不理人怎么办 支付宝本次交易嫌疑违规怎么办 支付宝一年的交易总额怎么办 交易关闭钱扣了怎么办 交易猫账号绑定支付宝打不开怎么办 拼多多涉假处罚怎么办 淘宝店铺重复铺货扣6分怎么办 帆布鞋子买大了怎么办 开淘宝店没销量怎么办 开淘宝店没有销量怎么办 淘宝买东西支付密码错了怎么办 淘宝登入密码忘记了怎么办 逛街时手机没电了怎么办 逛街手机没有电了怎么办 卖家拒收退回来怎么办 群英会奖池钱不够买超了怎么办 三星s8卡顿严重怎么办 三星s8变卡了怎么办 新开店铺没有人怎么办 电视显示没有usb设备怎么办 华为平板电脑触摸屏没反应怎么办 平板电脑液晶显示屏坏了怎么办