?? f04a33190bf9001b12afef0b7ec704e8
字號:
import org.w3c.dom.*; //XML的DOM實現(xiàn)
import java.io.*;
import javax.xml.parsers.*; //XML解析器接口
public class C11_6{
public static void main(String args[])
{
try
{
//創(chuàng)建一個解析器工廠對象factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
//對象builder代表了具體的DOM解析器
DocumentBuilder builder = factory.newDocumentBuilder();
/* builder的parse()方法接受一個XML文件名作為輸入?yún)?shù),
返回一個document對象,它包含了用builder解析XML文件生成的DOM文檔。 */
//對document對象操作由DOM函數(shù)指定。
Document document = builder.parse(new File("C11_6.xml"));
//去掉XML文檔中作為格式化內(nèi)容的空白,而映射在DOM樹中的不必要的Text Node對象。
document.normalize();
Element root=document.getDocumentElement(); //獲得根元素
String rootName=root.getNodeName();
System.out.print("XML文件根節(jié)點的名字:"+rootName);
NodeList nodelist=root.getChildNodes(); //獲得根元素的子節(jié)點列表
GetElement(nodelist);
}
catch(Exception e){ System.out.println(e);}
}
public static void GetElement(NodeList nodelist)
{ int size=nodelist.getLength();
for(int i=0;i<size;i++)
{ Node cnode = nodelist.item(i); //獲得子節(jié)點列表中的第i個節(jié)點
if(cnode.getNodeType() == Node.TEXT_NODE)
{
Text textNode=(Text)cnode;
String content=textNode.getWholeText();
if(content.equals("")){}
else System.out.print(content);
}
if( cnode.getNodeType() == Node.ELEMENT_NODE)
{
Element elementNode=(Element)cnode;
String name=elementNode.getNodeName();
System.out.print(name+": ");
NodeList nodelist1=elementNode.getChildNodes(); //獲得根元素的子節(jié)點列表
GetElement(nodelist1);
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -