JDOM解析XML文件!

package com.test;

import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.*;
import java.io.*;
import java.util.List;

public class JDomMain
{
    public void BuildXML() throws Exception
    {
        Element root,student,number,name,age;
               
        root = new Element("student-info");//生成根元素:student-info  
        student = new Element("student");//生成元素:student,该元素中将包含元素number,name,age
        number = new Element("number");
        name = new Element("name");
        age = new Element("age");
       
        Document doc = new Document(root);//将根元素植入文档doc中
       
        number.setText("001");
        name.setText("yinjinke");
        age.setText("24");
        student.addContent(number);
        student.addContent(name);
        student.addContent(age);
        root.addContent(student);
       
        Format format = Format.getCompactFormat();
        format.setEncoding("gb2312");//设置xml文件的字符为gb2312
        format.setIndent("  ");//设置xml文件的缩进为2个空格
       
        XMLOutputter XMLOut = new XMLOutputter(format);//在元素后换行,每一层元素缩排2格
        XMLOut.output(doc, new FileOutputStream("studentinfo.xml")); 
       
    }
    @SuppressWarnings("unchecked")
    public static void main(String[] args) 
    {
        /*
        JDomMain jd = new JDomMain();
        System.out.println("Now we build an XML document ... ");
        try 
        {
            jd.BuildXML();
        } 
        catch (Exception e) 
        {
            e.printStackTrace();
        }
        System.out.println("finished!");
        */
        
        
        SAXBuilder builder = new SAXBuilder();
        Document read_doc = new Document();
        try 
        {
            read_doc = builder.build("studentinfo.xml");
        } 
        catch (JDOMException e1) 
        {
            e1.printStackTrace();
        } 
        catch (IOException e1) 
        {
            e1.printStackTrace();
        }
        
        
        Element stu = read_doc.getRootElement();
        List<Element> list = stu.getChildren("student");
        for(int i = 0;i < list.size();i++)
        {
            Element e = list.get(i);
            String str_number = e.getChildText("number");
            String str_name = e.getChildText("name");
            String str_age = e.getChildText("age");
            System.out.println("--------STUDENT--------------");
            System.out.println("NUMBER:" + str_number);
            System.out.println("NAME:" + str_name);
            System.out.println("AGE:" + str_age);
            System.out.println("------------------------------");
        }      
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值