public static void domCreateXml() { Document d = getDocumentBuilder().newDocument(); d.setXmlStandalone(false); // 向dom树中添加根节点booklib Element booklib = d.createElement("BookLib"); // 将booklib添加到dom树中 d.appendChild(booklib); // 向BookLib根节点中添加子节点book // 将book节点添加到booklib根节点中 //创建一个map集合,把节点名称和内容添加进去 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循环将key对应的value值传递进去,增加新的节点之前要先往map集合中添加内容,名字后面的序号与i相对应,以递增的形式,否则会找不到对象 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)); } // 创建TransformerFactory对象 TransformerFactory tff = TransformerFactory.newInstance(); // 创建Transformer对象 try { Transformer tf = tff.newTransformer(); // 对xml文件进行换行 tf.setOutputProperty(OutputKeys.INDENT, "yes"); // 转换成xml文件 tf.transform(new DOMSource(d), new StreamResult(new File("booksTest.xml"))); } catch (Exception e) { e.printStackTrace(); } } 这种我觉得如果要创建多个book的子节点和内容的话,会比较方便
牛!强!强!