Beruflich Dokumente
Kultur Dokumente
Objectives :
To describe JDOM API
Read xml files using java programming
When to use?
You should use a JDOM parser when:
You need to know a lot about the structure of a
document
You need to move parts of the document around
you might want to sort certain elements.
For example:
You need to use the information in the
document more than once
You are a java developer and want to leverage
java optimized parsing of XML
3
JDOM classes
The JDOM defines several Java classes. Here are the
most common classes:
Example
Lets create the following file.xml file and put it in
local disk C
<?xml version="1.0"?>
<company>
<staff>
<firstname>Animaw</firstname>
<lastname>kerie</lastname>
<nickname>anex</nickname>
<salary>10000</salary>
</staff>
<staff>
<firstname>Ali</firstname>
<lastname>hussien</lastname>
<nickname>alex</nickname>
<salary>200000</salary>
</staff>
</company>
package parser;
try {
Document document =
(Document) builder.build(xmlFile);
Element rootNode =
document.getRootElement();
List list =
rootNode.getChildren("staff");
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
for (int i = 0; i < list.size(); i+
import org.jdom2.JDOMException;
+) {
import
Element node = (Element)
org.jdom2.input.SAXBuilder;
list.get(i);
public class Animaw {
public static void main(String[]
args) {
SAXBuilder builder = new
SAXBuilder();
File xmlFile = new
File("c:\\file.xml");
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"));
}
10
} catch (IOException io) {
Import XML-related
packages
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.jdom2.Document;
import org.jdom2.Element;
import
org.jdom2.JDOMException;
import
org.jdom2.input.SAXBuilder;
11
Create a DocumentBuilder
SAXBuilder builder = new
SAXBuilder();
Create a Document from a file or stream
Examinee attributes
//returns specific attribute
getAttribute("attributeName");
13
Assignment
Read and apply a demo example of:
SAX and DOM parsers
15