XML文件的生成
1.DOM方式生成xml
public void createDOMXml() throws Exception{
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
//创建一个DocumentBuider的对象
DocumentBuilder db=dbf.newDocumentBuilder();
//创建新的文档
org.w3c.dom.Document document = db.newDocument();
document.setXmlStandalone(true); //设置xml里面不显示standlone
//创建文档下的一个根节点
org.w3c.dom.Element bookstore = document.createElement("bookstore");
//向bookstore添加子节点
org.w3c.dom.Element book = document.createElement("book");
//book添加属性
book.setAttribute("id", "1");
//添加子节点
org.w3c.dom.Element name = document.createElement("name");
//name.setNodeValue("西游记"); //nodevalue 读取时为null
name.setTextContent("西游记");
org.w3c.dom.Element author = document.createElement("author");
author.setTextContent("吴承恩");
org.w3c.dom.Element year = document.createElement("year");
year.setTextContent("明朝");
org.w3c.dom.Element price = document.createElement("price");
price.setTextContent("110");
//添加子节点
book.appendChild(name);
book.appendChild(author);
book.appendChild(year);
book.appendChild(price);
//将book添加book
bookstore.appendChild(book);
//添加根节点(已经包含了book)
document.appendChild(bookstore);
//将dom树保存成xml文件
//创建TransformerFactory 对象
TransformerFactory factory=TransformerFactory.newInstance();
Transformer tf = factory.newTransformer();
//设置换行
tf.setOutputProperty(OutputKeys.INDENT,"yes");
//将document转换成xml文件
tf.transform(new DOMSource(document), new StreamResult(new File("book1.xml")) );
}
2.SAX方式生成xml
public void createSAXXml() throws Exception {
// 1.通过SAXParserFactory的静态newInstance()方法获取SAXParserFactord的实例factory
SAXParserFactory sf = SAXParserFactory.newInstance();
// 2.通过SAXParserFactory实例获取SAXParser实例
SAXParser paser = sf.newSAXParser();
// 3.创建SAXPraserHandler对象
SAXParserHandler ph = new SAXParserHandler();
// 4.解析xml文件
paser.parse("books.xml", ph);
List list = ph.getList();
// 生成xml 准备工作
// 1.创建TransformerFactory类对象
SAXTransformerFactory sttf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
//2.通过SAXTransformerFactory对象创建一个TransformerHandler对象
TransformerHandler handler = sttf.newTransformerHandler();
//3.通过handler对象创建一个Transformer对象
Transformer transformer = handler.getTransformer();
//4.通过transformer对象对象生成的xml文件进行设置
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");//设置编码格式
transformer.setOutputProperty(OutputKeys.INDENT,"yes");//设置换行
//5.创建一个Result对象 利用Result创建xml文件
File file = new File("src/res/newbooks.xml");
if(!file.exists()){
file.createNewFile();
}
Result result =new StreamResult(new FileOutputStream(file));
//6.将result和handler联系起来
handler.setResult(result); //在setResult前配置设置
//利用handler对象进行xml文件内容的编写
//打开documt
handler.startDocument();
AttributesImpl attr=new AttributesImpl();
//创建bookstore开始element 标签
handler.startElement("", "", "bookstore",attr);
for (Object book : list) {
System.out.println(book);
Book bk=(Book) book;
attr.clear();
attr.addAttribute("", "", "id", "",bk.getId() );
handler.startElement("", "", "book",attr);
//创建name节点
if(bk.getName()!=null&&!"".equals(bk.getName().trim())){
attr.clear();
handler.startElement("", "", "name",attr);
handler.characters(bk.getName().toCharArray(), 0, bk.getName().length());
handler.endElement("", "", "name");
}
//创建author节点
if(bk.getAuthor()!=null&&!"".equals(bk.getAuthor().trim())){
attr.clear();
handler.startElement("", "", "author",attr);
handler.characters(bk.getAuthor().toCharArray(), 0, bk.getAuthor().length());
handler.endElement("", "", "author");
}
//创建year节点
if(bk.getYear()!=null&&!"".equals(bk.getYear().trim())){
attr.clear();
handler.startElement("", "", "year",attr);
handler.characters(bk.getYear().toCharArray(), 0, bk.getYear().length());
handler.endElement("", "", "year");
}
//创建price节点
if(bk.getPrice()!=null&&!"".equals(bk.getPrice().trim())){
attr.clear();
handler.startElement("", "", "price",attr);
handler.characters(bk.getPrice().toCharArray(), 0, bk.getPrice().length());
handler.endElement("", "", "price");
}
//创建language节点
if(bk.getLanguage()!=null&&!"".equals(bk.getLanguage().trim())){
attr.clear();
handler.startElement("", "", "Language",attr);
handler.characters(bk.getLanguage().toCharArray(), 0, bk.getPrice().length());
handler.endElement("", "", "Language");
}
handler.endElement("", "", "book");
}
//创建bookstore结束element标签
handler.endElement("", "", "bookstore");
//关闭document
handler.endDocument();
}
3.DOM4J生成xml
public void createDOM4JXml() throws IOException{
//1.创建document对象,代表整个xml文档
org.dom4j.Document document = DocumentHelper.createDocument();
//2.创建根节点rss
org.dom4j.Element rss = document.addElement("rss");
//3.向rss节点中添加version属性
rss.addAttribute("version", "2.0");
//4.生成子节点及子节点的内容
org.dom4j.Element channel = rss.addElement("channel");
org.dom4j.Element title = channel.addElement("title");
title.setText("国内最新新闻");
org.dom4j.Element context = channel.addElement("context");
context.setText("尼玛。。。。。。。。。。。。。。");
org.dom4j.Element image = context.addElement("image");
image.setText("尼玛。。。。。。。。。。。。。。.jpg");
//5.设置生成xml格式
OutputFormat format=OutputFormat.createPrettyPrint();
//format.setEncoding("GBK");
//6.生成xml文件
File file=new File("rssnews.xml");
XMLWriter writer=new XMLWriter(new FileOutputStream(file),format);
//设置是否转义 默认true带表转义
writer.setEscapeText(false);
//写入文件
writer.write(document);
writer.close();
}
4.JDOM生成xml
public void creatJDOMXml() throws Exception{
//1.生成一个根节点
Element rss = new Element("rss");
//2.为节点添加属性
rss.setAttribute("version","2.0");
//3.生成一个document对象
Document document = new Document(rss);
//添加内容
Element channel=new Element("channel");
rss.addContent(channel);
Element title = new Element("title");
title.setText("国内最新新闻");
channel.addContent(title);
Element item = new Element("item");
//解决转义
CDATA cdata = new CDATA("<!啥会是开机快了]>");
item.addContent(cdata);
channel.addContent(item);
//创建format对象,对生成的format进行格式设置
Format format=Format.getCompactFormat();
format.setIndent("");
//4.创建XMLOutputter的对象
XMLOutputter outputter=new XMLOutputter(format);
//5.利用outputter将document对象转换成xml文档
outputter.output(document, new FileOutputStream(new File("rssnews.xml")));
}
四种生成xml文件对比
DOM ——-基于tree
SAX———-基于事件
JDOM,DOM4J————基于底层API
DOM与SAX
DOM树驻留到内存中 ,可以随时修改,增删
SAX生成也是事件驱动,事件结束不能回头修改 ,sax效率最高
DOM4J效率是相较与DOM和JDOM中比较高