Question_3
Add.java
Java XML 2016
package question_3;
import static controller.Document_DOM.getDocumentParse;
import static controller.SaveXML.saveXMLContent;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author Lonely
*/
public class Add {
public void Add(String id, String path) {
try {
Document d = getDocumentParse("src\\Data\\products.xml");
Element products = d.getDocumentElement();
//create element product
Element product = d.createElement("product");
product.setAttribute("id", id);
//create name tag
Element name = d.createElement("name");
name.appendChild(d.createTextNode("Mobile"));
product.appendChild(name);
//Create des tag
Element des = d.createElement("des");
des.appendChild(d.createTextNode("2016"));
product.appendChild(des);
//Create price tag
Element price = d.createElement("price");
price.appendChild(d.createTextNode("8833"));
product.appendChild(price);
//create catalog tag
Element catalog = d.createElement("catalog");
catalog.appendChild(d.createTextNode("ABC DEF"));
product.appendChild(catalog);
products.appendChild(product);
//Write to file
saveXMLContent(d, "src\\Data\\" + path);
System.out.println("===QUESTION [3] Add voi id moi thanh cong!");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Main.java
Java XML 2016
package run;
import question_1.CreateXML;
import question_2.ReadDOM;
import question_3.Add;
/**
*
* @author Lonely
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//1 Tạo file XML dùng DOM
CreateXML c = new CreateXML();
c.create();
//2 Đọc toàn bộ cấu trúc file XML (Hiển thị node gốc, các node con, value, attribute)
ReadDOM r = new ReadDOM();
r.Display();
//3 Thêm một node có product id = 999, các thông tin khác (name, price, des, catalog) tùy chọn và save vào file question_3.xml
Add s = new Add();
s.Add("999", "question_3.xml");
}
}
Run test
question_3.xml
0 nhận xét:
Post a Comment