首页 > 应用开发 > Java > 利用Jdom读取xml
新建 contents.xml
新建 SAXBuilderTest.java
//注意 /jdom.jar;./xerces.jar 加入到classpath中
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) {
}
}
}
来源:中国IT实验室收集整理
[@more@]来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/790981/viewspace-899425/ ,如需转载,请注明出处,否则将追究法律责任。