方法如下:
//创建xml的方法
public static void createxml() throws Exception{
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
DocumentBuilder db=dbf.newDocumentBuilder();
Document document= db.newDocument();
//创建一个bookstore节点
Element bookstore=document.createElement("bookstore");
Element book=document.createElement("book");
Element book1=document.createElement("book");
//创建一个name节点并添加在book下
Element name= document.createElement("name");
Element author= document.createElement("author");
Element name1= document.createElement("name");
Element author1= document.createElement("author");
book.appendChild(name);
book.appendChild(author);
book1.appendChild(name1);
book1.appendChild(author1);
//添加文本到name节点
name.setTextContent("小王子");
author.setTextContent("六爷");
name1.setTextContent("三体");
author1.setTextContent("刘慈欣");
//设置book属性名以及属性值
book.setAttribute("id", "1");
book1.setAttribute("id", "2");
//向bookstore根节点中添加子节点
bookstore.appendChild(book);
bookstore.appendChild(book1);
//添加跟节点
document.appendChild(bookstore);
//树的结构已经生成,接下来生成xml文件
//前几步都是一定的
TransformerFactory tft= TransformerFactory.newInstance();
Transformer tf= tft.newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
//创建新的xml文件并导入document
tf.transform(new DOMSource(document), new StreamResult(new File("book1.xml")));
}