public?static?void?domCreateXml()?{
Document?d?=?getDocumentBuilder().newDocument();
d.setXmlStandalone(false);
//?向dom樹中添加根節(jié)點booklib
Element?booklib?=?d.createElement("BookLib");
//?將booklib添加到dom樹中
d.appendChild(booklib);
//?向BookLib根節(jié)點中添加子節(jié)點book
//?將book節(jié)點添加到booklib根節(jié)點中
//創(chuàng)建一個map集合,把節(jié)點名稱和內(nèi)容添加進去
Map?<String,String>container?=?new?HashMap<String,String>();
container.put("name1",?"不錯的一本好書");
container.put("name2",?"nice?book");
container.put("author1",?"不錯");
container.put("author2",?"nice");
container.put("year1",?"2019");
container.put("year2",?"9102");
container.put("price1",?"100");
container.put("price2",?"001");
container.put("language1",?"Chinese");
container.put("language2",?"English");
//采用for循環(huán)將key對應(yīng)的value值傳遞進去,增加新的節(jié)點之前要先往map集合中添加內(nèi)容,名字后面的序號與i相對應(yīng),以遞增的形式,否則會找不到對象
for?(int?i?=?1;?i?<=?2;?i++)?{
Element?book?=?d.createElement("Book");
booklib.appendChild(book);
book.setAttribute("id",?String.valueOf(i));
//?添加name
Element?name?=?d.createElement("name");
book.appendChild(name);
name.setTextContent(container.get("name"+i));
//?添加author
Element?author?=?d.createElement("author");
book.appendChild(author);
author.setTextContent(container.get("author"+i));
//?添加year
Element?year?=?d.createElement("year");
book.appendChild(year);
year.setTextContent(container.get("year"+i));
//?添加price
Element?price?=?d.createElement("price");
book.appendChild(price);
price.setTextContent(container.get("price"+i));
//?添加language
Element?language?=?d.createElement("language");
book.appendChild(language);
language.setTextContent(container.get("language"+i));
}
//?創(chuàng)建TransformerFactory對象
TransformerFactory?tff?=?TransformerFactory.newInstance();
//?創(chuàng)建Transformer對象
try?{
Transformer?tf?=?tff.newTransformer();
//?對xml文件進行換行
tf.setOutputProperty(OutputKeys.INDENT,?"yes");
//?轉(zhuǎn)換成xml文件
tf.transform(new?DOMSource(d),?new?StreamResult(new?File("booksTest.xml")));
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
這種我覺得如果要創(chuàng)建多個book的子節(jié)點和內(nèi)容的話,會比較方便
2019-07-06
牛!強!強!