Dùng DOM thao tác dữ liệu XML trong Java


Đề bài
  •  Dùng Dom để thao tác với XML
Chi tiết như sau

Trong đây mình hướng dẫn các bạn sử dụng DOM để thao tác với XML cụ thể với Read, Insert, Update, Delete với file XML: TuDien.XML

0. Link:

Nguồn: Link tham khảo bài viết: Tải đây

1. Cấu trúc tập tin XML như sau:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<TuDien>
<AnhViet>
<TiengAnh>one</TiengAnh>
<TiengViet>một</TiengViet>
</AnhViet>
<AnhViet>
<TiengAnh>Two</TiengAnh>
<TiengViet>hai</TiengViet>
</AnhViet>
</TuDien>

2. Read
public static ArrayList<String> ReadNode(String pFilePath,
String pNodeName) throws Exception
{
ArrayList<String> ds = new ArrayList<String>();
InputSource xml = new InputSource(pFilePath);
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xml);

XPathFactory xpf = XPathFactory.newInstance();
XPath xpath = xpf.newXPath();
String exp = "//TuDien//AnhViet//" + pNodeName;

NodeList names = (NodeList) xpath.evaluate(exp, doc,
 XPathConstants.NODESET);
for(int i=0;i<names.getLength();i++)
{
Element elem = (Element)names.item(i);
ds.add(elem.getTextContent());
}
return ds;
}

public static ArrayList<String> ReadTiengAnh(String pFilePath){
try {
return ReadNode(pFilePath, "TiengAnh");
} catch (Exception ex) {
Logger.getLogger(ProcessXML.class.getName())
.log(Level.SEVERE, null, ex);
}
return null;
}
public static ArrayList<String> ReadTiengViet(String pFilePath){
try {
return ReadNode(pFilePath, "TiengViet");
} catch (Exception ex) {
Logger.getLogger(ProcessXML.class.getName())
.log(Level.SEVERE, null, ex);
}
return null;
}
public static ArrayList<ArrayList<String>> ReadTuDienFromXML(String pFilePath)
{
ArrayList<ArrayList<String>> mt = new ArrayList<ArrayList<String>>();
File f = new File(pFilePath);
if (!f.exists())//không tồn tại file XML
return mt;
mt.add(ReadTiengAnh(pFilePath));
mt.add(ReadTiengViet(pFilePath))
return mt;
}

kết quả: (mảng 2 chiều)

ReadTiengAnh: one | two
ReadTiengViet: một | hai

3. Insert

Insert dữ liệu XML có TextContent:

public static Document InsertAppendNode(String pFilePath,
 String pStrTiengAnh, String pStrTiengViet) throws Exception {
        File f = new File(pFilePath);
        Document doc = null;
        Element root = null;
        if (!f.exists()||index==0) {  //nếu như file đó không tồn tại
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().newDocument();
            root = doc.createElement("TuDien");
            doc.appendChild(root);
        } else {
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().parse(f);
            root = doc.getDocumentElement();
        }

        Element pAnhViet = doc.createElement("AnhViet");
        root.appendChild(pAnhViet);

        Element pTiengAnh = doc.createElement("TiengAnh");
        pTiengAnh.appendChild(doc.createTextNode(pStrTiengAnh));
        pAnhViet.appendChild(pTiengAnh);

        Element pTiengViet= doc.createElement("TiengViet");
        pTiengViet.appendChild(doc.createTextNode(pStrTiengViet));
        pAnhViet.appendChild(FileName);

        return doc;
    }

Insert dữ liệu XML có Attributes:

public static Document InsertAppendNode(String pFilePath,
 String pStrTiengAnh, String pStrTiengViet) throws Exception {
        File f = new File(pFilePath);
        Document doc = null;
        Element root = null;
        if (!f.exists()||index==0) {  //nếu như file đó không tồn tại
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().newDocument();
            root = doc.createElement("TuDien");
            doc.appendChild(root);
        } else {
            doc = DocumentBuilderFactory.newInstance().
                    newDocumentBuilder().parse(f);
            root = doc.getDocumentElement();
        }

        Element pAnhViet = doc.createElement("AnhViet");
pAnhViet.setAttribute("TiengAnh",pStrTiengAnh);
pAnhViet.setAttribute("TiengViet",pStrTiengViet);      
root.appendChild(pAnhViet);        return doc;
    }

4. Update

Update dữ liệu XML có TextContent:

public static void SearchAndUpdateTiengViet(Node node,
 String pStrTiengAnh, String pStrTiengViet) {
if (node == null)
{
  return;
}
  if (node.getNodeName().equals("TuDien"))
  {
  NodeList list = node.getChildNodes();
  for (int index = 0; index < list.getLength(); index++)
  {
  if (list.item(index).getNodeName().equals("AnhViet"))
{
 if (list.item(index).getTextContent().equals(pStrTiengAnh))
{
list.item(index + 1).setTextContent(pStrTiengViet);
return;
}
 }
  }
 }
NodeList children = node.getChildNodes();
for (int index = 0; index < children.getLength(); index++)
{
 SearchAndUpdateTiengViet(children.item(index),pStrTiengAnh, pStrTiengViet);
}
}

Update dữ liệu XML có Attributes:

public static void SearchAndUpdateTiengViet(Node node,
  String pStrTiengAnh, String pStrTiengViet) {
if (node == null)
{
  return;
}
 if (node.getNodeName().equals("AnhViet")) {
if (node.getAttributes().getNamedItem("TiengAnh").
getNodeValue().equals(pStrTiengAnh)) {
node.getAttributes().getNamedItem("TiengViet").
setNodeValue(pStrTiengViet);
return;
}
}
NodeList children = node.getChildNodes();
for (int index = 0; index < children.getLength(); index++) {
SearchAndUpdateTiengViet(children.item(index), pStrTiengAnh, pStrTiengViet);
}
}

5. Delete

Delete dữ liệu XML có TextContent:

public static Document SearchAndDeleteTiengViet(Node node, String pStrTiengViet) {
if (node == null) {
return;
}
if (node.getNodeName().equals("TuDien")) {
NodeList list = node.getChildNodes();
for (int index = 0; index < list.getLength(); index++) {
if (list.item(index).getNodeName().equals("AnhViet")) {
if (list.item(index).getTextContent().equals(pStrTiengViet)) {
node.getParentNode().removeChild(node);
return;
}
}
}
}
NodeList children = node.getChildNodes();
for (int index = 0; index < children.getLength(); index++) {
SearchAndDeleteTiengViet(children.item(index), pStrTiengViet);
}
}

Delete dữ liệu XML có Attributes:

public static void SearchAndDeleteTiengViet(Node node, String pStrTiengViet) {
if (node == null) {
return;
}
if (node.getNodeName().equals("AnhViet")) {
if (node.getAttributes().getNamedItem("TiengViet").
getNodeValue().equals(pStrTiengViet)) {
node.getParentNode().removeChild(node);
return;
}
}
NodeList children = node.getChildNodes();
for (int index = 0; index < children.getLength(); index++) {
SearchAndDeleteTiengViet(children.item(index), pStrTiengViet);
}
}

6. Xuất ra file XML

Các hàm trên chỉ hoạt động trên cây DOM nằm trong bộ nhớ mà chưa thực sự được ghi xuống vào CSDL. Nếu  muốn tất cả dữ liệu đã thao tác thì sau khi gọi hàm muốn sử dụng, xong thì phải gọi thêm 1 hàm nữa, để ghi toàn bộ cây DOM ra file XML.
public static void WriteAppendXML(String pFilePath, Document Doc) throws Exception
{
    File f = new File(pFilePath);
    Source source = new DOMSource(Doc);
    Result result = new StreamResult(f);
    Transformer trans = TransformerFactory.newInstance().
        newTransformer();
    trans.transform(source, result);
}

7. Thư viện sử dụng trong project
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

Post a Comment

Mới hơn Cũ hơn