創建一個DocumentBuilderFactory對象。
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
利用DocumentBuilderFactory對象來創建一個DocumentBuilder對象。
DocumentBuilder db = dbf.newDocumentBuilder();
通過DocumentBuilder對象的parse()方法來加載XML文件返回一個Document對象。
Document document = db.parse("File.xml"); //File.xml爲XML文件的路徑
使用Document對象去操作XML文件。
使用getElementsByTagName()方法來獲取節點集合,返回一個NodeList對象。
NodeList nodeList = document.getElementsByTagName("tagName"); //tagName爲節點名稱
遍歷NodeList中每一個節點。
for(int i = 0; i < nodeList.getLength(); i++){
//使用NodeList中的item()方法獲取一個節點,返回一個Node對象。
Node node = nodeList.item(i);
//遍歷節點中所有的屬性
//使用Node中的getAttributes()方法獲取節點的所有屬性的集合,返回一個NamedNodeMap對象。
/*
在知道屬性名的情況下,也可以把nodeList.item(i)返回的Node對象強制轉換爲Element對象來獲取相應的屬性的值。
如獲取屬性id的值:
Element ele = (Element) nodeList.item(i);
String attrValue = ele.getAttribute("id");
*/
NamedNodeMap attrs = node.getAttributes();
for(int j = 0; j < attrs.getLength(); j++){
//也是使用item()方法,返回一個Node對象
Node attr = attrs.item(j);
//獲取屬性名
String attrName = attr.getNodeName();
//獲取屬性值
String attrValue = attr.getNodeValue();
}
//遍歷節點中的子節點
//使用Node中的getChildNodes()方法獲取節點的所有子節點,返回一個NodeList對象。
NodeList childNodes = node.getChildNodes();
//需要注意的是Java在解析XML文件的時候會把開始標籤到結束標籤之間的所有內容都看成是該標籤的子節點,包括空格和換行。這一類沒有用標籤括起來的節點稱爲Text類型的節點,節點名叫#text。而有用標籤括起來的節點叫Element類型的節點。
for(int k = 0; k < childNodes.getLength(); k++){
//因爲上述的原因,我們需要區分出Text類型的節點和Element類型的節點。
if(childNodes.item(k).getNodeType() == Node.ELEMENT_NODE){ //判斷子節點的類型是否爲Element類型。
String childNodeName = childNodes.item(k).getNodeName(); //獲取子節點的節點名。
//在獲取子節點的節點值的時候不能單純使用childNodes.item(k).getNodeValue()方法,因爲子節點標籤之間的內容被看作的是子節點的子節點。應該爲:
String childNodeValue = childNodes.item(k).getTextContent();
// 或String childNodeValue = childNodes.item(k).getFirstChild().getNodeValue();
}
}
}
以上僅僅簡單的獲取了XML文件中的屬性名、屬性值、節點名和節點值。
Keep Going…