Bài 31-Xử lý XML File trong Kotlin


Chúng ta đã biết xử lý Text File, Serialize File, trong bài này Tui sẽ hướng dẫn các bạn cách lưu và đọc  dữ liệu với XML File.

Tui vẫn sử dụng các thư viện trong JVM để xử lý cho Kotlin. Cũng với ví dụ như các bài xử lý file trước đó, ta có lớp Sản phẩm với thông tin như sau:


import java.io.Serializable

/**
* Created by cafe on 02/06/2017.
*/
class SanPham {
var ma:Int=0
var ten:String=""
var donGia:Double=0.0
constructor()
constructor(ma: Int, ten: String, donGia: Double) {
this.ma = ma
this.ten = ten
this.donGia = donGia
}
override fun toString(): String {
return "$ma\t$ten\t$donGia"
}
}

Cấu trúc file XML Tui muốn các bạn phải lưu trữ thành:





  1
  Coca cola
  15.5


 2
 Sting
 25.0


 3
 Redbull
 17.0



Để lưu và đọc được XML File thì ta phải sử dụng các thư viện sau:

import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.TransformerFactory
import org.w3c.dom.Element

Tui có tạo 1 lớp XMLFileFactory có 2 phương thức để ghi file XML và đọc file XML. Các bạn muốn hiểu rõ thêm về XML thì nên học thêm các kiến thức về XML. Trong bài học này Tui cung cấp các  lệnh để các bạn có thể áp dụng vào việc ghi và đọc File (Tui không giải thích sâu, vì các bạn là dân lập trình nên chắc chắn đọc sẽ suy luận được. Nếu bạn khó hiểu thì cứ nhớ trong đầu như sau: Hàm LuuFile là hàm đưa dữ liệu danh sách Sản phẩm thành file XML, hàm DocFile mô hình hóa ngược lại từ tập dữ liệu XML thành hướng đối tượng trong Kotlin -là danh Sách Sản Phẩm).


import java.io.File
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.transform.stream.StreamResult
import javax.xml.transform.dom.DOMSource
import javax.xml.transform.TransformerFactory
import org.w3c.dom.Element

/**
* Created by cafe on 02/06/2017.
*/
class XMLFileFactory {
/**
* @author Trần Duy Thanh
* @param data: Dữ liệu là Danh sách sản phẩm muốn lưu
* @param path: Đường dẫn lưu trữ
* @return true nếu lưu thành công, false nếu lưu thất bại
*/
fun LuuFile(data:MutableList,path:String):Boolean
{
try
{
val docFactory = DocumentBuilderFactory.newInstance()
val docBuilder = docFactory.newDocumentBuilder()
// root elements
val doc = docBuilder.newDocument()
val rootElement = doc.createElement("SanPhams")
doc.appendChild(rootElement)
for(sp in data)
{
val sanPhamElement = doc.createElement("SanPham")
val maElement=doc.createElement("Ma")
maElement.textContent=sp.ma.toString()
sanPhamElement.appendChild(maElement)
val tenElement=doc.createElement("Ten")
tenElement.textContent=sp.ten
sanPhamElement.appendChild(tenElement)
val giaElement=doc.createElement("Gia")
giaElement.textContent=sp.donGia.toString()
sanPhamElement.appendChild(giaElement)
rootElement.appendChild(sanPhamElement);
}
// write the content into xml file
val transformerFactory = TransformerFactory.newInstance()
val transformer = transformerFactory.newTransformer()
val source = DOMSource(doc)

val result = StreamResult(File(path).absolutePath)

// Output to console for testing
// StreamResult result = new StreamResult(System.out);
transformer.transform(source, result)
return true
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return false
}

/**
* @author Trần Duy Thanh
* @param path:đường dẫn muốn đọc dữ liệu
* @return Danh sách sản phẩm MutableList
*/
fun DocFile(path:String):MutableList
{
var data:MutableList = mutableListOf()
try {
//Get the DOM Builder Factory
val factory = DocumentBuilderFactory.newInstance()

//Get the DOM Builder
val builder = factory.newDocumentBuilder()

//Load and Parse the XML document
//document contains the complete XML as a Tree.
val xmlfile = File(path)

val document = builder.parse(xmlfile)

//Iterating through the nodes and extracting the data.
val nodeList = document.documentElement.childNodes

for (i in 0..nodeList.length - 1) {

//We have encountered an  tag.
val node = nodeList.item(i)
if (node is Element) {
val sp = SanPham()
val childNodes = node.getChildNodes()
for (j in 0..childNodes.getLength() - 1) {
val cNode = childNodes.item(j)

//Identifying the child tag of employee encountered.
if (cNode is Element) {
val content = cNode.getLastChild().getTextContent().trim()
when (cNode.getNodeName()) {
"Ma" -> sp.ma= content.toInt()
"Ten" -> sp.ten= content
"Gia" -> sp.donGia= content.toDouble()
}
}
}
data.add(sp)
}
}
}
catch (ex:Exception)
{
ex.printStackTrace()
}
return data
}
}

Ta tạo một hàm main để thử nghiệm việc lưu XML FILE:


fun main(args: Array) {
var data:MutableList = mutableListOf()
var sp1=SanPham(1,"Coca cola",15.5)
data.add(sp1)
var sp2=SanPham(2,"Sting",25.0)
data.add(sp2)
var sp3=SanPham(3,"Redbull",17.0)
data.add(sp3)
var kqLuu= XMLFileFactory().LuuFile(data,"d:/dulieusanpham.xml")
if(kqLuu)
{
println("Lưu text file thành công")
}
else
{
println("Lưu text file thất bại")
}
}

Khi chạy hàm main ở trên thì ta có kết quả sau:

Lưu text file thành công

Bây giờ ta vào ổ D xem tập tin dulieusanpham.xml có được lưu thành công hay chưa:

Rõ ràng kết quả đã lưu thành công, bây giờ ta sẽ gọi hàm đọc thông tin lên nhé:


fun main(args: Array) {
var data:MutableList = XMLFileFactory().DocFile("d:/dulieusanpham.xml")
for (sp in data)
println(sp)
}

Khi chạy hàm main ở trên thì ta có kết quả sau:

1 Coca cola 15.5
2 Sting 25.0
3 Redbull 17.0

Như vậy ta đã lưu và đọc XML File thành công, các bạn tự áp dụng vào các dự án cụ thể nhé, cấu trúc XML File như thế nào là do bạn quyết định

Các bài sau Tui sẽ trình bày về Xử lý JSON File trong Kotlin rất quan trọng trong quá trình xử lý lưu trữ dữ liệu

Các bạn có thể tải source code bài này ở đây: http://www.mediafire.com/file/lh1024w1b722but/HocXMLFile.rar

Hẹn gặp các bạn ở những bài tiếp theo

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

Trần Duy Thanh (http://communityuni.com/)

One response

  1. […] bạn đã nắm được 3 kiểu tương tác File: Text File, Serialize File, XML file. Bây giờ Tui hướng dẫn loại định dạng file cuối cùng rất nổi tiếng hiện […]

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.