服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

使用jdom对xml文件进行操作的实例讲解

本文着重介绍在应用程序中如何使用jdom对xml文件进行操作,要求读者具有基本的java语言基础。

xml由于其可移植性,已经成为应用开发中必不可少的环节。我们经常会把应用程序的一些配置文件(属性文件)写成xml的格式(当然,也可以用property文件而不用xml文件),应用程序通过xml的访问类来对其进行操作。对xml进行操作可以通过若干种方法,如:sax, dom, jdom, jaxp等,jdom由于其比较简单实用而被开发人员普遍使用。

本文主要分两部分,第一部分介绍如何把xml文件中的配置读入应用程序中,第二部分介绍如何使用jdom将配置输出到xml文件中。

以下是一段xml配置文件,文件名为contents.xml:

<?xml version="1.0"?>
<book>
    <title>java and xml</title>
    <contents>
        <chapter title="introduction">
            <topic>xml matters</topic>
            <topic>what's important</topic>
            <topic>the essentials</topic>
            <topic>what&apos;s next?</topic>
        </chapter>
        <chapter title="nuts and bolts">
            <topic>the basics</topic>
            <topic>constraints</topic>
            <topic>transformations</topic>
            <topic>and more...</topic>
            <topic>what&apos;s next?</topic>
        </chapter>
    </contents>
</book>

下面的程序通过使用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) {
        }
    }
}

扫描关注微信公众号