public?static?void?domCreateXml()?{
Document?d?=?getDocumentBuilder().newDocument();
d.setXmlStandalone(false);
//?向dom樹(shù)中添加根節(jié)點(diǎn)booklib
Element?booklib?=?d.createElement("BookLib");
//?將booklib添加到dom樹(shù)中
d.appendChild(booklib);
//?向BookLib根節(jié)點(diǎn)中添加子節(jié)點(diǎn)book
//?將book節(jié)點(diǎn)添加到booklib根節(jié)點(diǎn)中
//創(chuàng)建一個(gè)map集合,把節(jié)點(diǎn)名稱和內(nèi)容添加進(jìn)去
Map?<String,String>container?=?new?HashMap<String,String>();
container.put("name1",?"不錯(cuò)的一本好書(shū)");
container.put("name2",?"nice?book");
container.put("author1",?"不錯(cuò)");
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對(duì)應(yīng)的value值傳遞進(jìn)去,增加新的節(jié)點(diǎn)之前要先往map集合中添加內(nèi)容,名字后面的序號(hào)與i相對(duì)應(yīng),以遞增的形式,否則會(huì)找不到對(duì)象
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對(duì)象
TransformerFactory?tff?=?TransformerFactory.newInstance();
//?創(chuàng)建Transformer對(duì)象
try?{
Transformer?tf?=?tff.newTransformer();
//?對(duì)xml文件進(jìn)行換行
tf.setOutputProperty(OutputKeys.INDENT,?"yes");
//?轉(zhuǎn)換成xml文件
tf.transform(new?DOMSource(d),?new?StreamResult(new?File("booksTest.xml")));
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
這種我覺(jué)得如果要?jiǎng)?chuàng)建多個(gè)book的子節(jié)點(diǎn)和內(nèi)容的話,會(huì)比較方便
2019-07-06
牛!強(qiáng)!強(qiáng)!