新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
關(guān)于Java讀取xml文件的學(xué)習(xí)
一.java類

- package com.java.test;
- import org.w3c.dom.*;
- import javax.xml.parsers.*;
- import java.io.*;
- public class JavaReadXml {
- // Document可以看作是XML在內(nèi)存中的一個(gè)鏡像,那么一旦獲取這個(gè)Document 就意味著可以通過對
- // 內(nèi)存的操作來實(shí)現(xiàn)對XML的操作,首先***步獲取XML相關(guān)的Document
- private Document doc = null;
- public void init(String xmlFile) throws Exception {
- // 很明顯該類是一個(gè)單例,先獲取產(chǎn)生DocumentBuilder工廠
- // 的工廠,在通過這個(gè)工廠產(chǎn)生一個(gè)DocumentBuilder,
- // DocumentBuilder就是用來產(chǎn)生Document的
- DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
- DocumentBuilder db = dbf.newDocumentBuilder();
- // 這個(gè)Document就是一個(gè)XML文件在內(nèi)存中的鏡像
- doc = db.parse(new File(xmlFile));
- }
- // 該方法負(fù)責(zé)把XML文件的內(nèi)容顯示出來
- public void viewXML(String xmlFile) throws Exception {
- this.init(xmlFile);
- // 在xml文件里,只有一個(gè)根元素,先把根元素拿出來看看
- Element element = doc.getDocumentElement();
- System.out.println("根元素為:" + element.getTagName());
- NodeList nodeList = doc.getElementsByTagName("person");
- System.out.println("book節(jié)點(diǎn)鏈的長度:" + nodeList.getLength());
- Node fatherNode = nodeList.item(0);
- System.out.println("父節(jié)點(diǎn)為:" + fatherNode.getNodeName());
- // 把父節(jié)點(diǎn)的屬性拿出來
- NamedNodeMap attributes = fatherNode.getAttributes();
- for (int i = 0; i < attributes.getLength(); i++) {
- Node attribute = attributes.item(i);
- System.out.println("book的屬性名為:" + attribute.getNodeName()
- + " 相對應(yīng)的屬性值為:" + attribute.getNodeValue());
- }
- NodeList childNodes = fatherNode.getChildNodes();
- System.out.println(childNodes.getLength());
- for (int j = 0; j < childNodes.getLength(); j++) {
- Node childNode = childNodes.item(j);
- // 如果這個(gè)節(jié)點(diǎn)屬于Element ,再進(jìn)行取值
- if (childNode instanceof Element) {
- // System.out.println("子節(jié)點(diǎn)名為:"+childNode.getNodeName()+"相對應(yīng)的值為"+childNode.getFirstChild().getNodeValue());
- System.out.println("子節(jié)點(diǎn)名為:" + childNode.getNodeName()
- + "相對應(yīng)的值為" + childNode.getFirstChild().getNodeValue());
- }
- }
- }
- public static void main(String[] args) throws Exception {
- JavaReadXml parse = new JavaReadXml();
- // 我的XML文件
- parse.viewXML("person.xml");
- }
- }
二.xml文件
wang laohu 25 中國郵電出版社 li junjia 24 清華大學(xué)出版社
三.輸出結(jié)果
根元素為:book
book節(jié)點(diǎn)鏈的長度:2
父節(jié)點(diǎn)為:person
9
子節(jié)點(diǎn)名為:first相對應(yīng)的值為wang
子節(jié)點(diǎn)名為:last相對應(yīng)的值為laohu
子節(jié)點(diǎn)名為:age相對應(yīng)的值為25
子節(jié)點(diǎn)名為:version相對應(yīng)的值為中國郵電出版社
當(dāng)前題目:關(guān)于Java讀取xml文件的學(xué)習(xí)
網(wǎng)頁URL:http://fisionsoft.com.cn/article/djcpeep.html


咨詢
建站咨詢
