Java讀取XML之ByDom
xml代碼:
<?xml version="1.0" encoding="GB2312"?> <RESULT> <VALUE> <NO>A1234</NO> <ADDR>鄭州市金水區(qū)</ADDR> </VALUE> <VALUE> <NO>B1234</NO> <ADDR>鄭州市二七區(qū)</ADDR> </VALUE> </RESULT>
Java代碼:
package com.util; import java.io.File; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class ReadXmlByDom { public static void main(String args[]) { File f = new File("F:\\car.xml"); Dom(f); } public static void Dom(File f) { // Document可以看作是XML在內(nèi)存中的一個(gè)鏡像,那么一旦獲取這個(gè)Document 就意味
//可以通過(guò)對(duì)內(nèi)存的操作來(lái)實(shí)現(xiàn)對(duì)XML的操作 // 首先第一步獲取XML相關(guān)的Document try { // 很明顯該類(lèi)是一個(gè)單例,先獲取產(chǎn)生DocumentBuilder工廠(chǎng) // 的工廠(chǎng),再通過(guò)這個(gè)工廠(chǎng)產(chǎn)生一個(gè)DocumentBuilder, // DocumentBuilder就是用來(lái)產(chǎn)生Document的 DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document doc = builder.parse(f); // 根節(jié)點(diǎn)獲得方法 // Element root=doc.getDocumentElement(); // System.out.println("根節(jié)點(diǎn)是"+root.getTagName()); NodeList nl = doc.getElementsByTagName("VALUE"); // 父節(jié)點(diǎn)獲得方法 // Node fatherNode=nl.item(0); // System.out.println("父節(jié)點(diǎn)是"+fatherNode.getNodeName()); // NamedNodeMap attributes=fatherNode.getAttributes(); // 遍歷XML for (int i = 0; i < nl.getLength(); i++) { System.out.println("車(chē)牌號(hào)是" + doc.getElementsByTagName("NO").item(i) .getFirstChild().getNodeValue()); System.out.println("車(chē)主地址是" + doc.getElementsByTagName("ADDR").item(i) .getFirstChild().getNodeValue()); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
result:
車(chē)牌號(hào)是A1234
車(chē)主地址是鄭州市金水區(qū)
車(chē)牌號(hào)是B1234
車(chē)主地址是鄭州市二七區(qū)
posted on 2011-08-22 17:00 日出星辰 閱讀(91) 評(píng)論(0) 編輯 收藏