Chinaunix首页 | 论坛 | 博客
  • 博客访问: 590848
  • 博文数量: 718
  • 博客积分: 4000
  • 博客等级: 上校
  • 技术积分: 4960
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-17 13:24
文章分类

全部博文(718)

文章存档

2011年(1)

2008年(717)

我的朋友

分类:

2008-10-17 13:29:11

    本文着重介绍在应用程序中如何使用JDOM对XML文件进行操作,要求读者具有基本的JAVA语言基础。
XML由于其可移植性,已经成为应用开发中必不可少的环节。我们经常会把应用程序的一些配置文件(属性文件)写成XML的格式(当然,也可以用property文件而不用XML文件),应用程序通过XML的访问类来对其进行操作。对XML进行操作可以通过若干种方法,如:SAX, DOM, JDOM, JAXP等,JDOM由于其比较简单实用而被开发人员普遍使用。
本文主要分两部分,第一部分介绍如何把XML文件中的配置读入应用程序中,第二部分介绍如何使用JDOM将配置输出到XML文件中。
以下是一段XML配置文件,文件名为contents.xml:


     and XML
    
        
            XML Matters
            What's Important
            The Essentials
            What's Next?
        
        
            The Basics
            Constraints
            Transformations
            And More...
            What's Next?
        
    


下面的程序通过使用JDOM中SAXBuilder类对contents.xml进行访问操作,把各个元素显示在输出console上,程序名为:SAXBuilderTest.java,内容如下:
------------------------------------------------------------------
import java.io.File;
import java.util.Iterator;
import java.util.List;

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

public class SAXBuilderTest {

    private static String titlename;

    private String chapter;

    private String topic;

    public static void main(String[] args) {
        try {
            SAXBuilder builder = new SAXBuilder();
            Document document = builder.build(new File("contents.xml"));
            Element root = document.getRootElement();

            Element title = root.getChild("title");
            titlename = title.getText();
            System.out.println("BookTitle: " + titlename);

            Element contents = root.getChild("contents");
            List chapters = contents.getChildren("chapter");

            Iterator it = chapters.iterator();
            while (it.hasNext()) {
                Element chapter = (Element) it.next();
                String chaptertitle = chapter.getAttributeValue("title");
                System.out.println("ChapterTitle: " + chaptertitle);

                List topics = chapter.getChildren("topic");
                Iterator iterator = topics.iterator();
                while (iterator.hasNext()) {
                    Element topic = (Element) iterator.next();
                    String topicname = topic.getText();
                    System.out.println("TopicName: " + topicname);
                }
            }
        } catch (Exception ex) {
        }
    }
}

[1]  

【责编:Peng】

--------------------next---------------------

阅读(223) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~