JDOM解析XML文件!

来源:互联网 发布:java没有main函数 编辑:程序博客网 时间:2024/04/27 19:41
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("------------------------------");        }          }}