To read an XML file with Jdom, you first create the document object with the build () method of the Org.jdom.input.SAXBuilder object, and then read the required content using the document class, element class, and so on. Ibm:developerworks China Station has a good example:
Java code
- <?xml version="1.0" encoding="UTF-8"?>
- <HD>
- <disk name="C" >
- <capacity>8G</capacity>
- <directories>200</directories>
- <files>1580</files>
- </disk>
- <disk name="D" >
- <capacity>10G</capacity>
- <directories>500</directories>
- <files>3000</files>
- </disk>
- </HD>
The above Sample.xml document describes the basic information of a hard disk in a computer (root node <HD> represent hard disk,<disk> tag represents hard disk partition, from its Name property can be seen two drive letter name "C" and "D" Partition Each partition contains <capacity>,<directories><files> three nodes, representing the partition's space size, number of directories, and number of files included.
The following program reads the information in this file:
Java code
- Import java.util.*;
- Import org.jdom.*;
- Import Org.jdom.input.SAXBuilder;
- Public class Sample1 {
- public static void Main (string[] args) throws exception{
- Saxbuilder sb=New Saxbuilder ();
- Document doc=sb.build ("sample.xml"); //Construct Document Object
- Element root=doc.getrootelement (); //Get root element
- List List=root.getchildren ("Disk"); Take all the elements named disk
- For (int i=0;i<list.size (); i++) {
- Element element= (Element) list.get (i);
- String Name=element.getattributevalue ("name");
- String Capacity=element.getchildtext ("Capacity"); Take the contents of the disk child element capacity
- String Directories=element.getchildtext ("directories");
- String files=element.getchildtext ("files");
- SYSTEM.OUT.PRINTLN ("Disk information:");
- SYSTEM.OUT.PRINTLN ("Partition drive letter:" +name);
- SYSTEM.OUT.PRINTLN ("Partition capacity:" +capacity);
- System.out.println ("Number of directories:" +directories);
- System.out.println ("Number of files:" +files);
- System.out.println ("-----------------------------------");
- }
- }
- }
Operation Result:
C:\java>java Sample1
Disk Information:
Partition Drive letter: C
Partition capacity: 8G
Number of catalogs: 200
Number of files: 1580
-----------------------------------
Disk Information:
Partition Drive letter: D
Partition capacity: 10G
Number of catalogs: 500
Number of files: 3000
Jdom Learning to read XML files