一:读取XML
- DOM解析
- SAX解析
- DOM4J解析
- JDOM解析
1.DOM解析:是把xml文件全部读到内存中。然后再进行解析。
<?xml version="1.0" encoding="UTF-8"?> <bookstore> <book id="1"> <name>冰与火之歌</name> <author>乔治马丁</author> <year>2014</year> <price>89</price> </book> <book id="2"> <name>安徒生童话</name> <year>2004</year> <price>77</price> <language>English</language> </book> </bookstore>
books.xml文件如上图
解析如下:
package com.imooc.domtest.test; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; public class DOMTest { public static void main(String[] args) { //创建一个DocumentBuilderFactory的对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //创建一个DocumentBuilder的对象 try { //创建DocumentBuilder对象 DocumentBuilder db = dbf.newDocumentBuilder(); //通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下 Document document = db.parse("books.xml"); //获取所有book节点的集合 NodeList bookList = document.getElementsByTagName("book"); //通过nodelist的getLength()方法可以获取bookList的长度 System.out.println("一共有" + bookList.getLength() + "本书"); //遍历每一个book节点 for (int i = 0; i < bookList.getLength(); i++) { System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容================="); //通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始 Node book = bookList.item(i); // 获取book节点的所有属性集合 NamedNodeMap attrs = book.getAttributes(); System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性"); // 遍历book的属性 for (int j = 0; j < attrs.getLength(); j++) { //通过item(index)方法获取book节点的某一个属性 Node attr = attrs.item(j); //获取属性名 System.out.print("属性名:" + attr.getNodeName()); //获取属性值 System.out.println("--属性值" + attr.getNodeValue()); } // //前提:已经知道book节点有且只能有1个id属性 // //将book节点进行强制类型转换,转换成Element类型 // Element book = (Element) bookList.item(i); // //通过getAttribute("id")方法获取属性值 // String attrValue = book.getAttribute("id"); // System.out.println("id属性的属性值为" + attrValue); //解析book节点的子节点 NodeList childNodes = book.getChildNodes(); //遍历childNodes获取每个节点的节点名和节点值 System.out.println("第" + (i+1) + "本书共有" + childNodes.getLength() + "个子节点"); for (int k = 0; k < childNodes.getLength(); k++) { //区分出text类型的node以及element类型的node if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) { //获取了element类型节点的节点名 System.out.print("第" + (k + 1) + "个节点的节点名:" + childNodes.item(k).getNodeName()); // 获取了element类型节点的节点值 System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue()); // System.out.println("--节点值是:" + childNodes.item(k).getTextContent()); } } System.out.println("======================结束遍历第" + (i + 1) + "本书的内容================="); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
2.SAX解析,handle像是驱动式进行读取XML文件
进行测试类
package com.imooc.test; import java.io.IOException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import com.imooc.entity.Book; import com.imooc.handler.SAXParserHandler; public class SAXTest { /** * @param args */ public static void main(String[] args) { //获取一个SAXParserFactory的实例 SAXParserFactory factory = SAXParserFactory.newInstance(); //通过factory获取SAXParser实例 try { SAXParser parser = factory.newSAXParser(); //获取SAXParserHandler实例 SAXParserHandler handler = new SAXParserHandler(); parser.parse("books.xml", handler); System.out.println("共有" + handler.getBookList().size() + "本书"); for (Book book : handler.getBookList()) { System.out.println(book.getId()); System.out.println(book.getName()); System.out.println(book.getAuthor()); System.out.println(book.getYear()); System.out.println(book.getPrice()); System.out.println(book.getLanguage()); System.out.println("----finish----"); } } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
//进行SAX解析的工具类
package com.imooc.handler; import java.util.ArrayList; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import com.imooc.entity.Book; public class SAXParserHandler extends DefaultHandler { String value = null; Book book = null; private ArrayList<Book> bookList = new ArrayList<Book>(); public ArrayList<Book> getBookList() { return bookList; } int bookIndex = 0; /** * 用来标识解析开始 */ @Override public void startDocument() throws SAXException { // TODO Auto-generated method stub super.startDocument(); System.out.println("SAX解析开始"); } /** * 用来标识解析结束 */ @Override public void endDocument() throws SAXException { // TODO Auto-generated method stub super.endDocument(); System.out.println("SAX解析结束"); } /** * 解析xml元素 */ @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { //调用DefaultHandler类的startElement方法 super.startElement(uri, localName, qName, attributes); if (qName.equals("book")) { bookIndex++; //创建一个book对象 book = new Book(); //开始解析book元素的属性 System.out.println("======================开始遍历某一本书的内容================="); // //已知book元素下属性的名称,根据属性名称获取属性值 // String value = attributes.getValue("id"); // System.out.println("book的属性值是:" + value); //不知道book元素下属性的名称以及个数,如何获取属性名以及属性值 int num = attributes.getLength(); for(int i = 0; i < num; i++){ System.out.print("book元素的第" + (i + 1) + "个属性名是:" + attributes.getQName(i)); System.out.println("---属性值是:" + attributes.getValue(i)); if (attributes.getQName(i).equals("id")) { book.setId(attributes.getValue(i)); } } } else if (!qName.equals("name") && !qName.equals("bookstore")) { System.out.print("节点名是:" + qName + "---"); } } @Override public void endElement(String uri, String localName, String qName) throws SAXException { //调用DefaultHandler类的endElement方法 super.endElement(uri, localName, qName); //判断是否针对一本书已经遍历结束 if (qName.equals("book")) { bookList.add(book); book = null; System.out.println("======================结束遍历某一本书的内容================="); } else if (qName.equals("name")) { book.setName(value); } else if (qName.equals("author")) { book.setAuthor(value); } else if (qName.equals("year")) { book.setYear(value); } else if (qName.equals("price")) { book.setPrice(value); } else if (qName.equals("language")) { book.setLanguage(value); } } @Override public void characters(char[] ch, int start, int length) throws SAXException { // TODO Auto-generated method stub super.characters(ch, start, length); value = new String(ch, start, length); if (!value.trim().equals("")) { System.out.println("节点值是:" + value); } } }
//book的实体类
package com.imooc.entity; public class Book { private String id; private String name; private String author; private String year; private String price; private String language; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } }
3.JDOM解析XML
maven中的depend的路劲
<!-- 解析XML文件jdom2.0系列 --> <dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.6</version> </dependency>
测试JDOM的test
package com.imooc.jdomtest; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import com.imooc.entity.Book; public class JDOMTest { private static ArrayList<Book> booksList = new ArrayList<Book>(); /** * @param args */ public static void main(String[] args) { // 进行对books.xml文件的JDOM解析 // 准备工作 // 1.创建一个SAXBuilder的对象 SAXBuilder saxBuilder = new SAXBuilder(); InputStream in; try { // 2.创建一个输入流,将xml文件加载到输入流中 in = new FileInputStream("src/res/books.xml"); InputStreamReader isr = new InputStreamReader(in, "UTF-8"); // 3.通过saxBuilder的build方法,将输入流加载到saxBuilder中 Document document = saxBuilder.build(isr); // 4.通过document对象获取xml文件的根节点 Element rootElement = document.getRootElement(); // 5.获取根节点下的子节点的List集合 List<Element> bookList = rootElement.getChildren(); // 继续进行解析 for (Element book : bookList) { Book bookEntity = new Book(); System.out.println("======开始解析第" + (bookList.indexOf(book) + 1) + "书======"); // 解析book的属性集合 List<Attribute> attrList = book.getAttributes(); // //知道节点下属性名称时,获取节点值 // book.getAttributeValue("id"); // 遍历attrList(针对不清楚book节点下属性的名字及数量) for (Attribute attr : attrList) { // 获取属性名 String attrName = attr.getName(); // 获取属性值 String attrValue = attr.getValue(); System.out.println("属性名:" + attrName + "----属性值:" + attrValue); if (attrName.equals("id")) { bookEntity.setId(attrValue); } } // 对book节点的子节点的节点名以及节点值的遍历 List<Element> bookChilds = book.getChildren(); for (Element child : bookChilds) { System.out.println("节点名:" + child.getName() + "----节点值:" + child.getValue()); if (child.getName().equals("name")) { bookEntity.setName(child.getValue()); } else if (child.getName().equals("author")) { bookEntity.setAuthor(child.getValue()); } else if (child.getName().equals("year")) { bookEntity.setYear(child.getValue()); } else if (child.getName().equals("price")) { bookEntity.setPrice(child.getValue()); } else if (child.getName().equals("language")) { bookEntity.setLanguage(child.getValue()); } } System.out.println("======结束解析第" + (bookList.indexOf(book) + 1) + "书======"); booksList.add(bookEntity); bookEntity = null; System.out.println(booksList.size()); System.out.println(booksList.get(0).getId()); System.out.println(booksList.get(0).getName()); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
4.DOM4J解析方式:
maven中depend
<!-- 解析XML文件dom4j --> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency>
DOM4J测试类
package com.imooc.dom4jtest; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.imooc.entity.Book; public class DOM4JTest { private static ArrayList<Book> bookList = new ArrayList<Book>(); /** * @param args */ public static void main(String[] args) { // 解析books.xml文件 // 创建SAXReader的对象reader SAXReader reader = new SAXReader(); try { // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。 Document document = reader.read(new File("src/res/books.xml")); // 通过document对象获取根节点bookstore Element bookStore = document.getRootElement(); // 通过element对象的elementIterator方法获取迭代器 Iterator it = bookStore.elementIterator(); // 遍历迭代器,获取根节点中的信息(书籍) while (it.hasNext()) { System.out.println("=====开始遍历某一本书====="); Element book = (Element) it.next(); // 获取book的属性名以及 属性值 List<Attribute> bookAttrs = book.attributes(); for (Attribute attr : bookAttrs) { System.out.println("属性名:" + attr.getName() + "--属性值:" + attr.getValue()); } Iterator itt = book.elementIterator(); while (itt.hasNext()) { Element bookChild = (Element) itt.next(); System.out.println("节点名:" + bookChild.getName() + "--节点值:" + bookChild.getStringValue()); } System.out.println("=====结束遍历某一本书====="); } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
四种解析方法的对比
利用junit进行测试编码测试
package com.parser.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.dom4j.DocumentException; import org.dom4j.io.SAXReader; import org.jdom2.Attribute; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import com.imooc.entity.Book; import com.imooc.handler.SAXParserHandler; public class ParseTest { public void domXmlParser() { ArrayList<Book> bookLists = new ArrayList<Book>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document document = db.parse("books.xml"); NodeList bookList = document.getElementsByTagName("book"); for (int i = 0; i < bookList.getLength(); i++) { Node book = bookList.item(i); Book bookEntity = new Book(); NamedNodeMap attrs = book.getAttributes(); for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); if (attr.getNodeName().equals("id")) { bookEntity.setId(attr.getNodeValue()); } } NodeList childNodes = book.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) { String name = childNodes.item(k).getNodeName(); String value = childNodes.item(k).getFirstChild().getNodeValue(); if (name.equals("name")) { bookEntity.setName(value); } else if (name.equals("author")) { bookEntity.setAuthor(value); } else if (name.equals("year")) { bookEntity.setYear(value); } else if (name.equals("price")) { bookEntity.setPrice(value); } else if (name.equals("language")) { bookEntity.setLanguage(value); } } } bookLists.add(bookEntity); bookEntity = null; } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void saxXmlParser(){ SAXParserFactory factory = SAXParserFactory.newInstance(); try { SAXParser parser = factory.newSAXParser(); SAXParserHandler handler = new SAXParserHandler(); parser.parse("books.xml", handler); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void jdomXmlParser() { ArrayList<Book> booksList = new ArrayList<Book>(); SAXBuilder saxBuilder = new SAXBuilder(); InputStream in; try { in = new FileInputStream("books.xml"); InputStreamReader isr = new InputStreamReader(in, "UTF-8"); org.jdom2.Document document = saxBuilder.build(isr); org.jdom2.Element rootElement = document.getRootElement(); List<org.jdom2.Element> bookList = rootElement.getChildren(); for (org.jdom2.Element book : bookList) { Book bookEntity = new Book(); List<Attribute> attrList = book.getAttributes(); for (Attribute attr : attrList) { String attrName = attr.getName(); String attrValue = attr.getValue(); if (attrName.equals("id")) { bookEntity.setId(attrValue); } } List<org.jdom2.Element> bookChilds = book.getChildren(); for (org.jdom2.Element child : bookChilds) { if (child.getName().equals("name")) { bookEntity.setName(child.getValue()); } else if (child.getName().equals("author")) { bookEntity.setAuthor(child.getValue()); } else if (child.getName().equals("year")) { bookEntity.setYear(child.getValue()); } else if (child.getName().equals("price")) { bookEntity.setPrice(child.getValue()); } else if (child.getName().equals("language")) { bookEntity.setLanguage(child.getValue()); } } booksList.add(bookEntity); bookEntity = null; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (JDOMException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void dom4jXmlParser(){ ArrayList<Book> booksList = new ArrayList<Book>(); SAXReader reader = new SAXReader(); try { org.dom4j.Document document = reader.read(new File("books.xml")); org.dom4j.Element bookStore = document.getRootElement(); List<org.dom4j.Element> bookEles = bookStore.elements(); for (org.dom4j.Element book : bookEles) { Book bookEntity = new Book(); List<org.dom4j.Attribute> bookAttrs = book.attributes(); for (org.dom4j.Attribute attr : bookAttrs) { if (attr.getName().equals("id")) { bookEntity.setId(attr.getValue()); } } List<org.dom4j.Element> bookss = book.elements(); for (org.dom4j.Element bookChild : bookss) { String name = bookChild.getName(); String value = bookChild.getStringValue(); if (name.equals("name")) { bookEntity.setName(value); } else if (name.equals("author")) { bookEntity.setAuthor(value); } else if (name.equals("year")) { bookEntity.setYear(value); } else if (name.equals("price")) { bookEntity.setPrice(value); } else if (name.equals("language")) { bookEntity.setLanguage(value); } } booksList.add(bookEntity); bookEntity = null; } } catch (DocumentException e) { e.printStackTrace(); } } @Test public void testPerformance() throws Exception{ System.out.println("性能测试:"); //测试DOM的性能: long start = System.currentTimeMillis(); domXmlParser(); System.out.println("DOM:"+ (System.currentTimeMillis() - start) ); //测试SAX的性能: start = System.currentTimeMillis(); saxXmlParser(); System.out.println("SAX:"+ (System.currentTimeMillis() - start) ); //测试JDOM的性能: start = System.currentTimeMillis(); jdomXmlParser(); System.out.println("JDOM:"+ (System.currentTimeMillis() - start) ); //测试DOM4J的性能: start = System.currentTimeMillis(); dom4jXmlParser(); System.out.println("DOM4J:"+ (System.currentTimeMillis() - start) ); } }
性能输入:
dom:67
sax:6
jdom:86
dom4j:72
在性能方面当然是sax解析速度较快。但是在java中常用的解析方式是dom4j。例如hibernate中就是用dom4j来进行解析配置文件。
在通用解析上用Dom方式进行解析的比较多。还可以解析一个dom对象的html文件等。
二:写XML
java 中直接写入xml文件
1,DOM方式写入XML 文件
package com.imooc.domtest.test; import java.io.File; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; import org.w3c.dom.Element; public class CreateXML { public DocumentBuilder getDocumentBuilder(){ // 创建一个DocumentBuilderFactory的对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // 创建DocumentBuilder对象 DocumentBuilder db =null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } return db; } /** * 生成xml */ public void createXML(){ 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"); // name.setNodeValue("小王子"); name.setTextContent("小王子"); book.appendChild(name); book.setAttribute("id", "1"); //将book节点添加到bookstore根节点中 bookstore.appendChild(book); //将bookstore节点(已经包含了book)添加到dom树中 document.appendChild(bookstore); //创建TransformerFactory对象 TransformerFactory tff = TransformerFactory.newInstance(); try { //创建Transformer对象 Transformer tf = tff.newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.transform(new DOMSource(document),new StreamResult(new File("books1.xml"))); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } public static void main(String[] args) { CreateXML creatXml = new CreateXML(); creatXml.createXML(); } }
2,SAX方式写入xml文件
在sax方式写入xml文件。
package com.imooc.test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import javax.xml.transform.Result; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; import com.imooc.entity.Book; public class SAXTestCreate { public static ArrayList<Book> bookList; static { Book b1 = new Book(); b1.setId("1"); b1.setName("冰与火之歌"); b1.setAuthor("乔治马丁"); b1.setYear("2014"); b1.setPrice("89"); Book b2 = new Book(); b2.setId("2"); b2.setName("安徒生童话"); b2.setAuthor("乔治马丁"); b2.setYear("2004"); b2.setPrice("77"); b2.setLanguage("English"); bookList.add(b1); bookList.add(b2); } public void createXML() { // 生成xml // 1.创建一个TransformerFactory类的对象 SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory .newInstance(); try { // 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 f = new File("src/res/newbooks.xml"); if (!f.exists()) { f.createNewFile(); } // 6.创建Result对象,并且使其与handler关联 Result result = new StreamResult(new FileOutputStream(f)); handler.setResult(result); // 7.利用handler对象进行xml文件内容的编写O // 打开document handler.startDocument(); AttributesImpl attr = new AttributesImpl(); handler.startElement("", "", "bookstore", attr); for (Book book : bookList) { attr.clear(); attr.addAttribute("", "", "id", "", book.getId()); handler.startElement("", "", "book", attr); // 创建name节点 if (book.getName() != null && !book.getName().trim().equals("")) { attr.clear(); handler.startElement("", "", "name", attr); handler.characters(book.getName().toCharArray(), 0, book .getName().length()); handler.endElement("", "", "name"); } // 创建year节点 if (book.getYear() != null && !book.getYear().trim().equals("")) { attr.clear(); handler.startElement("", "", "year", attr); handler.characters(book.getYear().toCharArray(), 0, book .getYear().length()); handler.endElement("", "", "year"); } // 创建author节点 if (book.getAuthor() != null && !book.getAuthor().trim().equals("")) { attr.clear(); handler.startElement("", "", "author", attr); handler.characters(book.getAuthor().toCharArray(), 0, book .getAuthor().length()); handler.endElement("", "", "author"); } // 创建price节点 if (book.getPrice() != null && !book.getPrice().trim().equals("")) { attr.clear(); handler.startElement("", "", "price", attr); handler.characters(book.getPrice().toCharArray(), 0, book .getPrice().length()); handler.endElement("", "", "price"); } // 创建language节点 if (book.getLanguage() != null && !book.getLanguage().trim().equals("")) { attr.clear(); handler.startElement("", "", "language", attr); handler.characters(book.getLanguage().toCharArray(), 0, book .getLanguage().length()); handler.endElement("", "", "language"); } handler.endElement("", "", "book"); } handler.endElement("", "", "bookstore"); // 关闭document handler.endDocument(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { SAXTestCreate test = new SAXTestCreate(); test.createXML(); } }
book.class为上一章解析xml的book类
3.DOM4J 生成xml文件
package com.imooc.dom4jtest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.dom4j.Document; import org.dom4j.DocumentHelper; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; public class DOM4JTest { private void createXML(){ //1.创建document对象,代表整个xml文档 Document document = DocumentHelper.createDocument(); //2.创建根节点rss Element rss = document.addElement("rss"); //3.向rss节点中添加version属性 rss.addAttribute("version", "2.0"); //4.生成子节点及节点内容 Element channel = rss.addElement("channel"); Element title = channel.addElement("title"); title.setText("<![CDATA[上海移动互联网产业促进中心正式揭牌 ]]>"); //5.设置生成xml的格式 OutputFormat format = OutputFormat.createPrettyPrint(); format.setEncoding("GBK"); //6.生成xml文件 File file = new File("rssnews.xml"); XMLWriter writer; try { writer = new XMLWriter(new FileOutputStream(file), format); //设置是否转义,默认值是true,代表转义 writer.setEscapeText(false); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * @param args */ public static void main(String[] args) { new DOM4JTest().createXML(); } }
4.JOM生成xml文件
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; public class JDOMTestCreate { private void createXML() { //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("<![CDATA[上海移动互联网产业促进中心正式揭牌 ]]>");
Element title = new Element("title");
CDATA cdata = new CDATA("上海移动互联网产业促进中心正式揭牌");
title.setContent(cdata);
channel.addContent(title); Format format = Format.getCompactFormat(); format.setIndent(""); format.setEncoding("GBK"); //4.创建XMLOutputter的对象 XMLOutputter outputer = new XMLOutputter(format); try { //5.利用outputer将document对象转换成xml文档 outputer.output(document, new FileOutputStream(new File("rssnews.xml"))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { JDOMTestCreate creater = new JDOMTestCreate(); creater.createXML(); } }
生成xml文件的速度测试:DOM生成可以进行频繁的修改节点信息。而sax生成则不能在生成节点信息之后再进行修改等操作。DOM4j和JDOM方式则基于java的基础api的方式进行了优化。
测试代码:
package com.create.test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import org.dom4j.DocumentHelper; import org.dom4j.io.OutputFormat; import org.dom4j.io.XMLWriter; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.junit.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; public class CreateTest { /** * DOM方式生成xml文档 */ private void DOMCreateXML() { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = null; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { e.printStackTrace(); } Document document = db.newDocument(); document.setXmlStandalone(true); Element bookstore = document.createElement("bookStore"); Element book = document.createElement("book"); Element name = document.createElement("name"); name.setTextContent("小王子"); book.appendChild(name); book.setAttribute("id", "1"); bookstore.appendChild(book); document.appendChild(bookstore); TransformerFactory tff = TransformerFactory.newInstance(); try { Transformer tf = tff.newTransformer(); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.transform(new DOMSource(document), new StreamResult(new File( "books1.xml"))); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } } /** * SAX方式生成xml文档 */ public void SAXCreateXML() { SAXTransformerFactory tff = (SAXTransformerFactory) SAXTransformerFactory .newInstance(); try { TransformerHandler handler = tff.newTransformerHandler(); Transformer tr = handler.getTransformer(); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.setOutputProperty(OutputKeys.INDENT, "yes"); File f = new File("books2.xml"); if (!f.exists()) { f.createNewFile(); } Result result = new StreamResult(new FileOutputStream(f)); handler.setResult(result); 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"); handler.endDocument(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } } /** * JDOM方式生成xml文档 */ private void JDOMCreateXML() { 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"); XMLOutputter outputer = new XMLOutputter(format); try { outputer.output(document, new FileOutputStream(new File("books3.xml"))); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * DOM4J方式生成xml文档 */ private void DOM4JCreateXML(){ 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"); File file = new File("books4.xml"); XMLWriter writer; try { writer = new XMLWriter(new FileOutputStream(file), format); writer.setEscapeText(false); writer.write(document); writer.close(); } catch (IOException e) { e.printStackTrace(); } } @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) ); } }
性能测试:
DOM:418
SAX:3
JDOM:158
DOM4J:59
在项目中常用的是DOM4J进行解析XMl和生成XML文件。