XMLParder using DOM – [Write XML]


Bài trước chúng ta đả bik cách để đọc 1 file XML qua bài này chúng ta sẻ tìm hiểu cách viết file XML.

Chúng ta cần viết file XML có nội dung như sau :

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
	<company>
		<staff id="10172271">
			<firstname>Kobee</firstname>
			<lastname>koboo</lastname>
			<address>24/3Y TN</address>
			<birthdate>Thu Oct 10 00:00:00 ICT 1991</birthdate>
		</staff>
	</company>

Chúng ta củng quay lại với đối tượng của chúng ta : Staff.java

package thaihoanghai.demo1;

import java.util.Date;

/**
 * @author kobee
 *
 */
public class Staff {
	private String id;
	private String firstname;
	private String lastName;
	private String address;
	private Date birthDate;

	public Staff(String id, String firstname, String lastName, String address,
			Date birthDate) {
		super();
		this.id = id;
		this.firstname = firstname;
		this.lastName = lastName;
		this.address = address;
		this.birthDate = birthDate;
	}
	// setter ... getter.....

	@Override
	public String toString() {
		return "Staff [id=" + id + ", firstname=" + firstname + ", lastName="
				+ lastName + ", address=" + address + ", birthDate="
				+ birthDate + "]";
	}			
}

Main của chúng ta

package thaihoanghai.demo1;

import java.util.Date;

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;

public class WriteXML {
	public static void main(String[] args) {
		try {
			DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
			DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
			// create Document XML 
			Document doc = dBuilder.newDocument();
			// create root Element with name is company
			Element rootElement = doc.createElement("company");
			// we add this root element into XML Document 
			doc.appendChild(rootElement);

			// Create Object Staff
			Staff myStaff = new Staff("10172271", "Kobee", "koboo","24/3Y TN" , new Date("10/10/1991"));
			// append child elements to root element
			rootElement.appendChild(createNodeStaff(doc, myStaff));

			// write the content into xml file and display result into Consonle
			Transformer transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			// assign XML Document into Source to export
			DOMSource source = new DOMSource(doc);

			// Out put file xml
			StreamResult fileResult = new StreamResult("D:\\staff.xml");
			// Out put console testing		
			StreamResult consoleResult = new StreamResult(System.out);
			// run transform to execute two result below
			transformer.transform(source, consoleResult);
			transformer.transform(source, fileResult);
			System.out.println("XML DOM Created Successfully...");

		} catch (Exception e) {	
			e.printStackTrace();
		}
	}
	/**
	 * Method is used to create Node Staff (Staff Element).	 
	 * @param doc : XML Document
	 * @param myStaff : Object Class Staff
	 * @return : Node Staff to append Root element
	 */
	private static Node createNodeStaff(Document doc, Staff myStaff){
		// create Element staff
		Element staff = doc.createElement("staff");
		// Assign attribute for Element
		staff.setAttribute("id", myStaff.getId());
		// We create Element's staff and append child into Staff element
		staff.appendChild(createStaffElements(doc, staff, "firstname", myStaff.getFirstname()));
		staff.appendChild(createStaffElements(doc, staff, "lastname", myStaff.getLastName()));
		staff.appendChild(createStaffElements(doc, staff, "address", myStaff.getAddress()));
		staff.appendChild(createStaffElements(doc, staff, "birthdate", myStaff.getBirthDate().toString()));
		return staff;
	}

	/**
	 * This method is used to create Element for Node.
	 * @param doc : XML Document
	 * @param element : Current element
	 * @param name : Name's element
	 * @param value : Value's element
	 * @return : Node Element to append it into Parent element
	 */
	private static Node createStaffElements(Document doc, Element element, String name, String value){
		// create Element
		Element node = doc.createElement(name);
		// Append child element into parent element
		node.appendChild(doc.createTextNode(value));
		return node;
	}
}

Chúc các bạn thành công

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: