XML檔案
<template><task id="ddd">aaa</task></template>
構建DOM
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(this.getClass().getResourceAsStream("/template.xml"));//這裡指的是src目錄下
增加元素
Element element = doc.createElement("task");//建立元素
element.setAttribute("id","AAA");//新增屬性
element.appendChild(doc.createTextNode("DDD"));//新增文字節點
doc.getDocumentElement().appendChild(element);//追加到根節點元素中
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(this.getClass().getResource("/template.xml").getPath()));
transformer.transform(source, result);//寫入到檔案
刪除元素
doc.getDocumentElement().removeChild(doc.getElementsByTagName("task").item(0));//刪除根節點中第一個task元素
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
MSource source = new DOMSource(doc);
StreamResult result = new StreamResult(new FileOutputStream(this.getClass().getResource("/template.xml").getPath()));
transformer.transform(source, result);//寫入到檔案
修改元素
doc.getElementsByTagName("task").item(0).getFirstChild().setNodeValue("ccc");//修改第一個task元素中的內容
TransformerFactory tFactory =TransformerFactory.newInstance();
Transformer transformer = tFactory.newTransformer();
OMSource source = new DOMSource(doc);StreamResult result = new StreamResult(new FileOutputStream(this.getClass().getResource("/template.xml").getPath()));
transformer.transform(source, result);//寫入到檔案
檢視元素
NodeList tasks = doc.getDocumentElement().getChildNodes();
for(int i = 0;i < tasks.getLength();i++){
System.out.println(((Element)tasks.item(i)).getAttribute("id"));//輸出元素的id屬性值
System.out.println(tasks.item(i).getNodeValue);//輸出元素的內容值
}