1. 程式人生 > >Java基礎之XML(DOM解析和建立)

Java基礎之XML(DOM解析和建立)

程式碼如下:

package com.briup.DOMXML;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
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.NodeList;
import org.xml.sax.SAXException;

public class DOMXMLTest {
	private List<Student> list;
	private String Address[] = { "湖南", "上海", "湖北", "新疆", "北京", "天津", "河北" };
	private String Name[] = { "張三", "李四", "小米", "小明", "王五", "胡六", "利利" };

	public DOMXMLTest() {
		this.list = new ArrayList<Student>();
	}

	public void FileWriterStudentXML(String address) {
		// /樹結構的建立xml檔案
		// /第一步:建立一個檔案解析工廠
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		// /第二步:建立一個元件檔案
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
			// /第三步:建立一個檔案
			Document dcm = db.newDocument();
			// /建立一個根目錄
			Element stus = dcm.createElement("stus");
			dcm.appendChild(stus);
			/*
			 * // /第三步:獲取個體 Element stu = dcm.createElement("stu");
			 * stus.appendChild( stu ); // /第四步:獲取stu的屬性 stu.setAttribute("id",
			 * "t1"); stu.setAttribute("name", "張三"); ///第五步:獲取子標籤 Element child
			 * = dcm.createElement("address"); child.setTextContent("湖南");
			 * stu.appendChild( child );
			 */
			// /獲取10個個體
			for (int i = 0; i < 10; i++) {
				// /新建一個個體
				Element stu = dcm.createElement("stu");
				stus.appendChild(stu);
				// /第四步:獲取stu的屬性
				stu.setAttribute("id", "t" + i + 1);
				stu.setAttribute("name",
						Name[(int) (Math.random() * Name.length)]);
				// /第五步:獲取子標籤
				Element child = dcm.createElement("address");
				child.setTextContent(Address[(int) (Math.random() * Address.length)]);
				stu.appendChild(child);
			}
			// Text ContentAddress = dcm.createTextNode("湖南");
			// child.appendChild( ContentAddress );
			// /開始元件
			TransformerFactory tff = TransformerFactory.newInstance();
			Transformer tff2 = tff.newTransformer();
			tff2.transform(new DOMSource(dcm), new StreamResult(new File(
					address)));

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}

	public void SaveDataatList(String Address) {
		Student stu = null;
		try {
			// /建立一個dom的解析工廠
			DocumentBuilderFactory domparsefactory = DocumentBuilderFactory
					.newInstance();
			// /建立一個dom的解析
			DocumentBuilder domparse = domparsefactory.newDocumentBuilder();
			// /新建解析檔案xml
			File file = new File(Address);
			Document parse = domparse.parse(file);
			// /儲存屬性的根節點
			NodeList fatherNode = parse.getElementsByTagName("stu");
			for (int i = 0; i < fatherNode.getLength(); i++) {
				// /讀取每一個節點
				Element fatherElement = (Element) fatherNode.item(i);
				stu = new Student();
				// /獲取id和money的屬性值
				String id = fatherElement.getAttribute("id").trim();
				stu.setId(id);
				String name = fatherElement.getAttribute("name").trim();
				stu.setName(name);
				// /獲取子屬性的值
				NodeList childNode = fatherElement.getChildNodes();
				for (int j = 0; j < childNode.getLength(); j++) {
					if (childNode.item(j).getNodeType() == 1) {
						Element childElement = (Element) childNode.item(j);
						String address = childElement.getFirstChild().getNodeValue();
						stu.setAddress(address);
					}
				}
				list.add(stu);
			}
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void printList() {
		System.out.println("總共存在student:" + list.size());
		for (int i = 0; i < list.size(); i++)
			System.out.println(list.get(i).toString());
	}

	public static void main(String[] args) {
		String address = "src/com/briup/DOMXML/Stus.xml";
		DOMXMLTest te = new DOMXMLTest();
		// /元件一個Stus.xml檔案
		te.FileWriterStudentXML(address);
		// /儲存資料到list中
		te.SaveDataatList(address);
		// /列印資料
		te.printList();
	}
}

StusXml檔案自動建立:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<stus>
	<stu id="t01" name="小明">
		<address>湖北</address>
	</stu>
	<stu id="t11" name="小明">
		<address>天津</address>
	</stu>
	<stu id="t21" name="胡六">
		<address>湖南</address>
	</stu>
	<stu id="t31" name="李四">
		<address>湖南</address>
	</stu>
	<stu id="t41" name="小明">
		<address>河北</address>
	</stu>
	<stu id="t51" name="王五">
		<address>湖北</address>
	</stu>
	<stu id="t61" name="李四">
		<address>河北</address>
	</stu>
	<stu id="t71" name="王五">
		<address>天津</address>
	</stu>
	<stu id="t81" name="王五">
		<address>新疆</address>
	</stu>
	<stu id="t91" name="胡六">
		<address>河北</address>
	</stu>
</stus>

StudentJava檔案:

package com.briup.DOMXML;

public class Student {
	private String id;
	private String name;
	private String address;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", address=" + address
				+ "]";
	}

	public Student(String id, String name, String address) {
		this.id = id;
		this.name = name;
		this.address = address;
	}
 
	public Student() {
		
	}
}