?? ch12_4_1.java~1~
字號:
/* 程序范例: Ch12_4_1.java */
import javax.xml.parsers.*;
import org.xml.sax.*;
import java.io.*;
import org.w3c.dom.*;
public class Ch12_4_1 {
//聲明XML文件
static Document document;
public static void main(String[] args) throws Exception {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 設(shè)定解析的叁數(shù)
dbf.setIgnoringComments(true);
dbf.setIgnoringElementContentWhitespace(true);
DocumentBuilder db = dbf.newDocumentBuilder();
//導(dǎo)入XML文件
document = db.parse(new File("Ch12-4.xml"));
// 獲取根元素
Node root = document.getDocumentElement();
System.out.println("根元素: " + root.getNodeName());
NodeList nodes = root.getChildNodes();
// 獲取所有的子節(jié)點
for (int i=0; i < nodes.getLength(); i++) {
// 元素和文字節(jié)點
System.out.println("元素: " + nodes.item(i).getNodeName());
if (nodes.item(i).hasChildNodes()) {
NodeList childs = nodes.item(i).getChildNodes();
// 顯示所有子節(jié)點
for (int j=0; j < childs.getLength(); j++) {
int type = childs.item(j).getNodeType();
if (type == Node.ELEMENT_NODE) {
System.out.print(" +-- " + childs.item(j).getNodeName());
System.out.println("/" + childs.item(j).getFirstChild().getNodeValue());
}
}
}
}
// 顯示指定元素的屬性值
NodeList tagNodes = document.getElementsByTagName("book");
for (int i=0; i< tagNodes.getLength(); i++) {
System.out.println("book(" + i + "):");
NamedNodeMap atts = tagNodes.item(i).getAttributes();
for (int j = 0; j < atts.getLength(); j++) {
Node att = atts.item(j);
System.out.print(" +-- " + att.getNodeName());
System.out.println("/" + att.getNodeValue());
}
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -