本文着重先容在应用措施中如何利用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'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'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) {
}
}
}