JDOM is, quite simply, a Java representation of an XML document. JDOM
provides a way to represent that document for easy and efficient
reading, manipulation, and writing. It has a straightforward API, is a
lightweight and fast, and is optimized for the Java programmer. It’s an
alternative to DOM and SAX, although it integrates well with both DOM
and SAX.
この例では、JDOMを使用してXMLファイルを読み込み、各要素を順番に出力する方法を示します。
1. JDOMライブラリをダウンロードする
JDOMは、JDKにバンドルされているSAXやDOMのようなものではありません。 JDOMを使用するには、ライブラリを手動でダウンロードする必要があります。
JDOM official site
からJDOMを入手するか、Mavenを使用している場合は以下の依存関係を宣言してください。
<dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>1.1</version> </dependency>
2. XMLファイル
次のようにXMLファイル
<?xml version="1.0"?> <company> <staff> <firstname>yong</firstname> <lastname>mook kim</lastname> <nickname>mkyong</nickname> <salary>100000</salary> </staff> <staff> <firstname>low</firstname> <lastname>yin fong</lastname> <nickname>fong fong</nickname> <salary>200000</salary> </staff> </company>
3. Javaファイル
上記のXMLファイルを解析するには、JDOMパーサーを使用します。
import java.io.File; import java.io.IOException; import java.util.List; import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; public class ReadXMLFile { public static void main(String[]args) { SAXBuilder builder = new SAXBuilder(); File xmlFile = new File("c:\\file.xml"); try { Document document = (Document) builder.build(xmlFile); Element rootNode = document.getRootElement(); List list = rootNode.getChildren("staff"); for (int i = 0; i < list.size(); i++) { Element node = (Element) list.get(i); System.out.println("First Name : " + node.getChildText("firstname")); System.out.println("Last Name : " + node.getChildText("lastname")); System.out.println("Nick Name : " + node.getChildText("nickname")); System.out.println("Salary : " + node.getChildText("salary")); } } catch (IOException io) { System.out.println(io.getMessage()); } catch (JDOMException jdomex) { System.out.println(jdomex.getMessage()); } } }
出力
First Name : yong Last Name : mook kim Nick Name : mkyong Salary : 100000 First Name : low Last Name : yin fong Nick Name : fong fong Salary : 200000
-
注意** 次の2つの例もあります:
-
link://java/how-to-read-xml-file-in-java-sax-parser/[XMLの読み方
Javaのファイル – (SAX Parser)]** link://java/how-to-read-xml-file-in-java-dom-parser/[XMLの読み方
Javaのファイル – (DOM Parser)]
リンク://タグ/java/[java]リンク://タグ/jdom/[jdom]リンク://タグ/xml/[xml]