Thứ Ba, 27 tháng 11, 2012

Java : Xử lý tập tin Xml dùng JDOM

Trong Java, tùy theo nhu cầu và mục đích xử lý tập tin Xml, ta có nhiều lựa chọn. Dưới đây, ta dùng JDOM để đọc, viết, sửa, thêm nốt (node) con, thêm thuộc tính (attribute) cho một nốt. JDOM có thể được tải về tại đây.
Nội dung tập tin Xml "mobile phone.xml" cần đọc xem tại đây

Ta tạo thư mục dự án (project) trong Eclipse có cấu trúc sau, trong ví dụ ta dùng jdom-2.0.4:



Nội dung mã trong tập tin JDomTest.java
package xml.test;

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

import org.jdom2.Attribute;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.junit.Assert;
import org.junit.Test;

public class JDomTest {
 private static Runtime runtime = Runtime.getRuntime();
 
 @Test
 public void readWriteXmlWithJDom() {
  try {
   long startTime = System.currentTimeMillis();
   System.out.println("Before reading file : " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes" );
   SAXBuilder sb = new SAXBuilder();
   File f = new File("resources/mobile phone.xml");
   Document doc = sb.build(f);
   Element elementRoot = doc.getRootElement();
   List appList = elementRoot.getChildren("mobile_phone");
   
   Element phone = appList.get(0);
   
   Element phoneToAdd = phone.clone();
   // add attribute
   phoneToAdd.setAttribute(new Attribute("newAttr", "new value"));
   // add element
   elementRoot.addContent(phoneToAdd);
   
   Assert.assertEquals("smartphone", phone.getAttribute("category").getValue());
   phone.getChild("name").setText("HTC Desire");
   phone.getChild("manufacturer").setText("HTC");
   phone.getChild("description").setText("smartphone of HTC");
   System.out.println("After generating JDOM objects : " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes" );
   
   // write modified xml to file
   XMLOutputter xo = new XMLOutputter();
   xo.setFormat(Format.getPrettyFormat());
   xo.output(doc, new FileWriter("resources/jdom output mobile.xml"));
   
   long endTime = System.currentTimeMillis();
   System.out.println("After writing to XML file : " + (runtime.totalMemory() - runtime.freeMemory()) + " bytes" );
   System.out.println("Execution time : " +(endTime - startTime) + " mili seconds");
  } catch (JDOMException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

Giải thích mã:
- Ngoài phần dùng JDOM để xử lý tập tin xml, còn có thêm phần mã để tính thời gian và bộ nhớ tiêu thụ trong quá trình đó.
- Đầu tiên SAXBuilder được dùng để đọc và phân tích tập tin "mobile phone.xml" vào cấu trúc Document.
- Lấy nốt mobile_phone đầu tiên, phone, trong nốt gốc. Sao chép nội dung của nó vào nốt phoneToAdd.
- Thêm thuộc tính mới newAttr cùng nội dung của nó vào nốt vừa tạo.
- Thêm nốt phoneToAdd vừa tạo vào nốt gốc.
- Tiếp theo, kiểm tra giá trị của thuộc tính category của nốt phone đúng là "smartphone". Sau đó thay đổi nội dung các nốt con của nó.
- Ghi nội dung toàn bộ Document vừa thay đổi vào tập tin "jdom output mobile.xml" dùng XMLOutputter.

Nhận xét:
- JDOM cho phép ta đọc, chỉnh sửa hay thêm nội dung trong quá trình đọc và sau cùng lưu lại nội dung vừa thay đổi.
- JDOM cũng như DOM đọc toàn bộ nội dung tập tin xml và lưu nó trong bộ nhớ. Do đó tương tự, dùng JDOM tốn nhiều bộ nhớ đặc biệt khi đọc những tập tin dung lượng lớn.
- Ưu điểm của JDOM so với DOM là khi dùng, ta viết mã ít và gọn hơn và dễ dàng hơn. Nhưng nhược điểm, theo cá nhân tôi, thì JDOM tốn nhiều bộ nhớ và thời gian hơn DOM.

Không có nhận xét nào:

Đăng nhận xét