DOM和SAX方式是JAVA官方提供的方式,可以生成一个XML文件来存储信息,DOM4J和JDOM是非官方的方式,可以生成一个RSS文件
DOMTest:
public class DOMTest {
/*生成xml*/
public void createXML() throws Exception{
DocumentBuilder db=getDocumentBuilder();
Document document=db.newDocument();
Element bookstore=document.createElement("bookStore");
//向bookstore根节点中添加字节点book
Element book=document.createElement("book");
Element name=document.createElement("name");
book.appendChild(name);
name.setTextContent("小王子");
book.setAttribute("id", "1");
//将book节点添加到bookstore根节点中
bookstore.appendChild(book);
//将bookstore节点(已经包含了book),添加到dom树中
document.appendChild(bookstore);
//创建TransformerFactory对象
TransformerFactory tff=TransformerFactory.newInstance();
//创建Transformer对象
Transformer tf=tff.newTransformer();
//换行文件内容
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(document), new StreamResult(new File("boos1.xml")));
}
public static void main(String []args) throws Exception{
DOMTest test=new DOMTest();
test .createXML();
}
}
/**
* @Decription TODO sax方法创建一个xml文档
*/
public void saxCreateXml(){
//1、创建一个SAXTransformerFactory一个对象
SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
OutputStream in =null;
try {
//2、通过SAXTransformerFactory创建一个TransformerHandler对象
TransformerHandler handler = sf.newTransformerHandler();
//3、通过TransformerHandler对象获取Transformer对象(用于设置xml输出的样式和头)
Transformer transformer = handler.getTransformer();
//设置没有其他的DTD(Document Type Defination 文档类型定义)规范
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
//设置编码格式,显式的显示在中
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
//设置换行
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//文件输出
File file =new File("LocListSax.xml");
//确保file是存在的
if(!file.exists()){
if(!file.createNewFile()){
throw new FileNotFoundException("文件创建失败!");
}
}
//4、创建输出流OutputStream对象
in = new FileOutputStream(file);
//5、创建流Result对象
Result result = new StreamResult(in);
//6、关联result,此时有了生成元素的方法(handler提供的方法)和装元素的容器(result对象)
handler.setResult(result);
//打开文档
handler.startDocument();
//属性设置
AttributesImpl attr = new AttributesImpl();
//开始创建元素
handler.startElement("", "", "Location", attr);
attr.addAttribute("", "", "Name", "", "阿尔巴尼亚");
attr.addAttribute("", "", "Code", "", "DZA");
handler.startElement("", "", "CountryRegion", attr);
attr.clear();
attr.addAttribute("", "", "Name", "", "阿德拉尔");
attr.addAttribute("", "", "Code", "", "ADR");
handler.startElement("", "", "State", attr);
handler.endElement("", "", "State");
handler.endElement("", "", "CountryRegion");
//结束元素创建
handler.endElement("", "", "Location");
//关闭文档
handler.endDocument();
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
//关闭流, 习惯不好,老是不喜欢关闭流
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class JDOMTest {
private void createXML() 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("<国内最新新闻>");
//设置转义字符符号
title.setContent(new CDATA(""));
//
//title.setText(new CDATA("<国内最新新闻>"));//这样子可以处理特殊字符
channel.addContent(title);
//设置生成xml的格式
Format format=Format.getCompactFormat();
format.setIndent("");
//生成不一样的编码
format.setEncoding("GBK");
//4.创建XMLOutputter的对象
XMLOutputter outputter=new XMLOutputter(format);
//5.利用outputter将document对象转换成xml文档
outputter.output(document, new FileOutputStream(new File("rssnews.xml")));
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
new JDOMTest().createXML();
}
}
运行结果为:
创建的文件(rssnews.xml)
<rss version="2.0">
<channel>
<title>]]>title>
channel>
rss>
public class DOM4JTest {
private void createXML() throws Exception{
//1.创建document对象,代表整个xml文档
Document document=DocumentHelper.createDocument();
//2.创建根节点
Element rss=document.addElement("rss");
//3.向rss节点中添加version,自动生成默认编码模式(UTF-8)
rss.addAttribute("version", "2.0");
//4.生成子节点及节点内容
Element channel=rss.addElement("channel");
Element title=channel.addElement("title");
//title.setText("中国最新新闻");
title.setText("");
//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();
}
/**
* @param args
*/
public static void main(String[] args) throws Exception{
new DOM4JTest().createXML();
}
}
运行结果为:
rssnews.xml
<rss version="2.0">
<channel>
<title><!CDATA上海移动互联网产业促进中心正式揭牌]]>title>
channel>
rss>
public class CreateTest {
/**
* DOM方式生成xml文档
*/
public void DOMCreateXML() throws Exception{
// 创建一个DocumentBuilderFactory
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// 创建一个DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
//DocumentBuilder db=getDocumentBuilder();
Document document=db.newDocument();
document.setXmlStandalone(true);
Element bookstore=document.createElement("bookStore");
//向bookstore根节点中添加字节点book
Element book=document.createElement("book");
Element name=document.createElement("name");
book.appendChild(name);
name.setTextContent("小王子");
book.setAttribute("id", "1");
//将book节点添加到bookstore根节点中
bookstore.appendChild(book);
//将bookstore节点(已经包含了book),添加到dom树中
document.appendChild(bookstore);
//创建TransformerFactory对象
TransformerFactory tff=TransformerFactory.newInstance();
//创建Transformer对象
Transformer tf=tff.newTransformer();
//换行文件内容
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.transform(new DOMSource(document), new StreamResult(new File("books1.xml")));
}
/**
* SAX方式生成xml文档
*/
public void SAXCreateXML() throws Exception{
//生成XML
//1.创建一个TransformerFactory类的对象
SAXTransformerFactory tff=(SAXTransformerFactory) SAXTransformerFactory.newInstance();
//2.通过SAXTransformerFactory对象创建一个TransformerHandler对象
TransformerHandler handler= tff.newTransformerHandler();
//3.通过handler对象创建一个Transformer
Transformer tr=handler.getTransformer();
//4.通过Transformer对象对生成的xml文件进行设置
//设置xml的编码
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//设置xml的“是否换行”
tr.setOutputProperty(OutputKeys.INDENT, "yes");
//5.创建一个Result对象
File file=new File("books2.xml");
if (!file.exists()) {
file.createNewFile();
}
//6.创建Result对象,并且使其与handler关联
Result result=new StreamResult(new FileOutputStream(file));
handler.setResult(result);
//7.利用handler对象进行xml文件内容的编写
//打开document
handler.startDocument();
AttributesImpl attr=new AttributesImpl();
handler.startElement("", "", "bookstore", attr);
attr.clear();
attr.addAttribute("", "", "id", "", "1");
handler.startElement("", "", "book", attr);
attr.clear();
handler.startElement("", "", "name", attr);
handler.characters("小王子".toCharArray(), 0, "小王子".length());
handler.endElement("", "", "name");
handler.endElement("", "", "book");
handler.endElement("", "", "bookstore");
// 关闭document
handler.endDocument();
}
/**
* JDOM方式生成xml文档
*/
private void JDOMCreateXML() throws Exception{
org.jdom2.Element bookstore=new org.jdom2.Element("bookstore");
org.jdom2.Document document=new org.jdom2.Document(bookstore);
org.jdom2.Element book=new org.jdom2.Element("book");
book.setAttribute("id","1");
org.jdom2.Element name=new org.jdom2.Element("name");
name.setText("小王子");
book.addContent(name);
bookstore.addContent(book);
Format format=Format.getCompactFormat();
format.setIndent("");
//生成不一样的编码
format.setEncoding("UTF-8");
//4.创建XMLOutputter的对象
XMLOutputter outputter=new XMLOutputter(format);
//5.利用outputter将document对象转换成xml文档
outputter.output(document, new FileOutputStream(new File("books3.xml")));
}
/**
* DOM4J方式生成xml文档
*/
private void DOM4JCreateXML() throws Exception{
org.dom4j.Document document=DocumentHelper.createDocument();
org.dom4j.Element bookstore=document.addElement("bookstore");
org.dom4j.Element book=bookstore.addElement("book");
book.addAttribute("id", "1");
org.dom4j.Element name=book.addElement("name");
name.setText("小王子");
OutputFormat format=OutputFormat.createPrettyPrint();
//生成不一样的编码
format.setEncoding("UTF-8");
//6.生成xml文件
File file=new File("books4.xml");
XMLWriter writer=new XMLWriter(new FileOutputStream(file),format);
//设置是否转义,默认设置是true,代表转义
writer.setEscapeText(false);
writer.write(document);
writer.close();
}
@Test
public void testPerformance() throws Exception{
System.out.println("性能测试:");
//测试DOM的性能
long start=System.currentTimeMillis();
DOMCreateXML();
System.out.println("DOM:"+(System.currentTimeMillis()-start));
//测试SAX的性能
start=System.currentTimeMillis();
SAXCreateXML();
System.out.println("SAX:"+(System.currentTimeMillis()-start));
//测试JDOM的性能
start=System.currentTimeMillis();
JDOMCreateXML();
System.out.println("JDOM:"+(System.currentTimeMillis()-start));
//测试DOM4J
start=System.currentTimeMillis();
DOM4JCreateXML();
System.out.println("DOM4J:"+(System.currentTimeMillis()-start));
}
}