java是一种可以撰写跨平台应用软件的面向对象的程序设计语言,是由Sun Microsystems公司于1995年5月推出的Java程序设计语言和Java平台(即JavaEE, JavaME, JavaSE)的总称。本站提供基于Java框架struts,spring,hibernate等的桌面应用、web交互及移动终端的开发技巧与资料
保持永久学习的心态,将成就一个优秀的你,来 继续搞起java知识。
方法如下:
//创建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")));
}
java代码xmldom
因为水平有限,难免有疏忽或者不准确的地方,希望大家能够直接指出来,我会及时改正。一切为了知识的分享。
后续会有更多的精彩的内容分享给大家。
支付宝扫一扫
微信扫一扫
