XML小練習:利用DOM解析XML(利用遞歸,實用性強)

XML文件(student.xml):
<?xml version="1.0" encoding="utf-8"?>
<學生名冊 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="student.xsd" >
<!-- 這不是演習,這不是演習 -->	
	<學生 學號="1">
		<姓名>張三</姓名>
		<性別>男</性別>
		<年齡>20</年齡>
	</學生>
	<學生 學號="2">
		<姓名>李四</姓名>
		<性別>女</性別>
		<年齡>19</年齡>
	</學生>
	<學生 學號="3">
		<姓名>王五</姓名>
		<性別>男</性別>
		<年齡>21</年齡>
	</學生>
</學生名冊>




JAVA實現:
package com.xml.dom;

import java.io.File;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Domtest2 {
	public static void main(String[] args) throws Exception {

		// 獲取DOM解析器工廠
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		// 獲得具體的DOM解析器
		DocumentBuilder db = dbf.newDocumentBuilder();
		// 解析XML文檔,獲得Document對象(根結點)
		Document document = db.parse(new File("student.xml"));
		
                //獲取根元素
		Element root = document.getDocumentElement();

		parseElement(root);// 開始解析

		System.out.println("\n\nxml文件解析完成");
	}

	private static void parseElement(Element element) {
		String tagName = element.getNodeName();

		System.out.print("<" + tagName);

		parseAttr(element);

		NodeList children = element.getChildNodes();

		for (int i = 0; i < children.getLength(); i++) {
			Node node = children.item(i);

			short nodeType = node.getNodeType();

			if (nodeType == Node.ELEMENT_NODE)// 如果是元素格式
			{
				parseElement((Element) node);// 遞歸
			} else if (nodeType == Node.TEXT_NODE)// 如果是文本格式,直接輸出
			{
				System.out.print(node.getNodeValue());
			} else if (nodeType == Node.COMMENT_NODE)// 如果是註釋格式,獲取註釋內容後輸出
			{
				System.out.print("<!--");
				Comment comment = (Comment) node;
				String data = comment.getData();
				System.out.print(data + "-->");
			}
		}
		System.out.print("</" + tagName + ">");
	}

	// 解析該元素是否有屬性
	private static void parseAttr(Element element) {
		NamedNodeMap map = element.getAttributes();

		if (map != null) {
			for (int i = 0; i < map.getLength(); i++) {
				System.out.print(" | " + map.item(i).getNodeName() + "="
						+ map.item(0).getNodeValue());
			}
			System.out.print(">");
		} else {
			System.out.print(">");
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章