XML解析器常见的有两种:
1.SAX解析器,用于xml的简单API
2.DOM解析器,文档对象模型
DOM就是利用对象来把文本模型化,但是模型实现有以下几个基本的点:
1. 用来表示、操作文档的接口
2.接口行为、属性
3.接口之间的关系和互属性
在DOM接口中有四个基本接口:Document、Node、NodeList、NamedNodeMap
Node对象:DOM中最基本的对象
Document对象:代表整个XML文档
NodeList对象包含一个或者是多个Node的列表
Element对象代表xml文档中的标签元素
创建xml
/创建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")));
}
