使用DOM組裝和解析xml

package com.test;

import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

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

/**
 * @說明 使用DOM組裝和解析XML
 * @author cuisuqiang
 * @version 1.0
 * @since
 */
public class DomDemo{
	
	public static void main(String[] args) {
		DomDemo d = new DomDemo();
		String file = "C:\\p.xml"; // 文件存放位置
		d.createXml(file);
		d.parserXml(file);
	}

	/**
	 * 生成XML文件
	 * @param filePath 文件存放位置
	 */
	public void createXml(String filePath) {
		try {
			// 定義工廠 API,使應用程序能夠從 XML 文檔獲取生成 DOM 對象樹的解析器
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			// 定義 API, 使其從 XML 文檔獲取 DOM 文檔實例。使用此類,應用程序員可以從 XML 獲取一個 Document
			DocumentBuilder builder = factory.newDocumentBuilder();
			// Document 接口表示整個 HTML 或 XML 文檔。從概念上講,它是文檔樹的根,並提供對文檔數據的基本訪問
			Document document = builder.newDocument();
			
			Element root = document.createElement("persons");
			document.appendChild(root);
			Element person = document.createElement("person");
			Element name = document.createElement("name");
			name.appendChild(document.createTextNode("java小強"));
			person.appendChild(name);
			Element sex = document.createElement("sex");
			sex.appendChild(document.createTextNode("man"));
			person.appendChild(sex);
			Element age = document.createElement("age");
			age.appendChild(document.createTextNode("30"));
			person.appendChild(age);
			root.appendChild(person);
			
			TransformerFactory tf = TransformerFactory.newInstance();
			// 此抽象類的實例能夠將源樹轉換爲結果樹
			Transformer transformer = tf.newTransformer();
			DOMSource source = new DOMSource(document);
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			// 一個節點後換行,你可以設置爲true,然後嘗試解析看打印結果
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			// 向文本輸出流打印對象的格式化表示形式
			// 要保證你的文本輸出後格式不亂碼,打印對象需指定打印格式,以標記此文本支持的格式
			PrintWriter pw = new PrintWriter(filePath, "utf-8");
			// 充當轉換結果的持有者,可以爲 XML、純文本、HTML 或某些其他格式的標記
			StreamResult result = new StreamResult(pw);
			transformer.transform(source, result);
			System.out.println("生成XML文件成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 解析XML
	 * @param filePath 文件位置
	 */
	public void parserXml(String filePath) {
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			Document document = db.parse(filePath);
			// 接口提供對節點的有序集合的抽象,沒有定義或約束如何實現此集合。DOM 中的 NodeList 對象是活動的
			// NodeList 中的項可以通過從 0 開始的整數索引進行訪問
			NodeList xml = document.getChildNodes();
			for (int i = 0; i < xml.getLength(); i++) {
				Node roots = xml.item(i);
				NodeList persons = roots.getChildNodes();
				for (int j = 0; j < persons.getLength(); j++) {
					Node person = persons.item(j);
					NodeList pros = person.getChildNodes();
					for (int k = 0; k < pros.getLength(); k++) {
						Node item = pros.item(k);
						System.out.println(item.getNodeName() + ":" + item.getTextContent());
					}
				}
			}
			System.out.println("XML解析完畢");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

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