?? deptjdom.java
字號:
package firstjdom;
import java.io.*;
import org.jdom.input.*;
import org.jdom.output.*; //寫出DOM樹到文件
import org.jdom.*; //JDOM對象
import java.util.*;
//利用JDOM來遍歷 XML文件 輸出其中的元素
public class DeptJDom {
public static void printchild(Element e, int pos) {
//按層次進行縮進
String s = " ";
for (int i = 0; i < 3 * pos; i++) {
s += " ";
}
//元素是否有子元素
if (e.getChildren() != null) {
//得到所有的孩子節點
List l = e.getChildren();
for (int i = 0; i < l.size(); i++) {
Element ee = (Element) l.get(i);
//元素節點的名字
System.out.print(s + ee.getName() + " ");
//顯示屬性
List attrs = ee.getAttributes();
for (int j = 0; j < attrs.size(); j++) {
Attribute a = (Attribute) attrs.get(j);
System.out.print(a.getName() + "=" + a.getValue() + " ");
}
System.out.println();
//元素的值
System.out.println(s+s+ee.getValue());
//遞歸訪問
printchild(ee, pos + 1);
}
}
else { //顯示文本對象(文本元素)
//getText() 得到文本元素的值
//System.out.println(e.getName());
//System.out.println(s + " " + e.getText());
}
}
public static void main(String[] args) throws Exception {
//得到一個解析器SAX
//可以讀XML大型文件
org.jdom.input.SAXBuilder builder
= new org.jdom.input.SAXBuilder();
//得到JDOM樹
org.jdom.Document doc = builder.build("f:/dept.xml");
//得到根元素
//Element元素
//getRootElement() 得到根元素
Element e = doc.getRootElement();
System.out.print(e.getName());
//getAttributes() 得到元素的屬性
//Attribute表示屬性
List lattr = e.getAttributes();
for (int i = 0; i < lattr.size(); i++) {
Attribute attr = (Attribute) lattr.get(i);
//getName() 屬性名
//getValue() 屬性的值
System.out.print(attr.getName() + "=" + "\"" + attr.getValue() + " ");
}
System.out.println();
//以根為起點進行遍歷
printchild(e, 0);
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -