在java對XML進行處理時,讀取XML文檔,對其處理,這是我得一個執行個體代碼。
import java.io.FileInputStream;
import javax.xml.parsers.*;
import org.w3c.dom.*;
/*
* Created on 2004-6-2
*java讀取XML文檔
*利用DoM來讀取一個XML文檔的內容,並將其列印出來
*/
public class TestXML {
public static void main(String[] args) {
Document doc;
DocumentBuilderFactory factory;
DocumentBuilder docBuilder;
Element root;
String elementName;
FileInputStream in;
String fileName;
try{
//get the xml file
fileName = System.getProperty("user.dir");
fileName = fileName+"/sample.xml";
in = new FileInputStream(fileName);
//解析XML檔案,產生document對象
factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
docBuilder = factory.newDocumentBuilder();
doc = docBuilder.parse(in);
//解析成功
System.out.println("parse successfull");
//擷取XML文檔的根節點
root = doc.getDocumentElement();
elementName = root.getNodeName();
//列印根節點的屬性
printAttributes(root);
//列印該文檔全部節點
System.out.println("列印全部節點");
printElement(root,0);
}
catch(Exception exp){
exp.printStackTrace();
}
}
//列印某個節點的全部屬性
public static void printAttributes(Element elem){
NamedNodeMap attributes;
int i,max;
String name,value;
Node curNode;
attributes = elem.getAttributes();
max = attributes.getLength();
for(i=0;i<max;i++){
curNode = attributes.item(i);
name = curNode.getNodeName();
value = curNode.getNodeValue();
System.out.println("/t"+name+" = "+value);
}
}
//列印所有的節點的名稱和值
//改方法採用遞迴方式列印文檔的全部節點
public static void printElement(Element elem,int depth){
String elementName;
NodeList children;
int i,max;
Node curChild;
Element curElement;
String nodeName,nodeValue;
//elementName = elem.getNodeName();
//擷取輸入節點的全部子節點
children = elem.getChildNodes();
//按一定格式列印輸入節點
for(int j=0;j<depth;j++){
System.out.print(" ");
}
printAttributes(elem);
//採用遞迴方式列印全部子節點
max = children.getLength();
for(i=0;i<max;i++){
curChild = children.item(i);
//遞迴允出準則
if(curChild instanceof Element){
curElement = (Element)curChild;
printElement(curElement,depth+1);
}
else{
nodeName = curChild.getNodeName();
nodeValue = curChild.getNodeValue();
for(int j=0;j<depth;j++)System.out.print(" ");
System.out.println(nodeName+" = "+nodeValue);
}
}
}
}